public frmFileOptions(ProjectFile myFile)
        {
            InitializeComponent();

            this.myFile = myFile;

            this.Text = "Set Compiler Options for " + myFile.FileName;

            txtFileOpts.Text = myFile.Options;
        }
        private bool IsFileMain(ProjectFile file)
        {
            string fileContents = GetFileContents(file);

            try
            {
                fileContents = CodePreProcess.StripComments(fileContents);
            }
            catch (Exception ex)
            {
                TextBoxModify(outputTextbox, "####Error: could not strip comments from " + file.FileName + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
            }

            fileContents = fileContents.Replace('\r', ' ').Replace('\n', ' ');

            string re1 = "((?:[a-z][a-z0-9_]*))";	// return type
            string re2 = "(\\s+)";	// White Space
            string re3 = "(main)";	// main
            string re4 = "(\\s*)";	// optional white space
            string re5 = "(\\()";	// (
            string re6 = "([^)]*)";	// anything goes
            string re7 = "(\\))";	// )
            string re8 = "(\\s*)";	// optional white space
            string re9 = "(\\{)";	// {

            Regex r = new Regex(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9, RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Match m = r.Match(fileContents);
            if (m.Success)
            {
                return true;
            }

            return false;
        }
        private void JoinPDEFiles(ProjectFile file, StreamWriter writer, string prototypes)
        {
            try
            {
                writer.WriteLine("#line 1 \"{0}\"", file.FileName);
                string fileContent = File.ReadAllText(file.FileAbsPath);
                
                // function prototypes need to be inserted before the first non-preprocessor statement
                fileContent = InsertAtFirstStatement(fileContent, prototypes);

                writer.WriteLine(fileContent);
            }
            catch (Exception ex)
            {
                TextBoxModify(outputTextbox, "####Error while joining " + file.FileName + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
            }
        }
        private bool HandleArduino(ref string objFiles, ref string avr_ar_targets)
        {
            bool result = true;

            bool ardJoinStarted = false;
            ProjectFile ardFile = null;
            StreamWriter ardWriter = null;
            List<string> ardLibList = new List<string>();

            List<string> functProto = GetAllFunctProto(); // use regex to gather a list of function prototypes
            string allPrototypes = "";
            // gather all the prototypes in one line
            foreach (string proto in functProto)
            {
                allPrototypes += proto;
            }

            foreach (ProjectFile file in workingFileList.Values)
            {
                if (file.Exists && file.ToCompile && file.FileExt == "pde")
                {
                    if (ardJoinStarted == false)
                    {
                        // this is the first .pde file, do the stuff that must be done once here

                        // join all the .pde files into one cpp file
                        string tempArduinoPath = SettingsManagement.AppDataPath + "temp" + Path.DirectorySeparatorChar + "arduino_temp_main.cpp";
                        ardFile = new ProjectFile(tempArduinoPath, workingProject);

                        Program.MakeSurePathExists(SettingsManagement.AppDataPath + "temp");

                        try
                        {
                            ardWriter = new StreamWriter(ardFile.FileAbsPath);

                            ardWriter.WriteLine("#include <WProgram.h>"); // required for arduino functions to work
                            ardWriter.WriteLine("extern \"C\" void __cxa_pure_virtual() {}"); // required to prevent a compile error
                            ardWriter.Flush();

                            if (workingProject.OverrideArduinoCore)
                                workingProject.IncludeDirList.Add(workingProject.ArduinoCoreOverride);
                            else
                                workingProject.IncludeDirList.Add(SettingsManagement.ArduinoCorePath);

                            ardLibList.Clear();

                            ardJoinStarted = true;
                        }
                        catch (Exception ex)
                        {
                            TextBoxModify(outputTextbox, "####Error while writing " + ardFile.FileName + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
                        }
                    }

                    // join all the .pde files into one cpp file
                    // while tracking all the libraries being used and inserting function prototypes
                    JoinPDEFiles(file, ardWriter, allPrototypes);
                }
            }

            if (ardJoinStarted) // if arduino files exist, or else skip this since the main.cxx will interfer
            {
                List<ProjectFile> ardExtList = new List<ProjectFile>();

                try
                {
                    // append the final bit
                    ardWriter.WriteLine("#line 1 \"arduinomain.cpp\"");
                    ardWriter.WriteLine(GetPDEMain()); // get from either existing file or internal resource
                    ardWriter.Close();
                }
                catch (Exception ex)
                {
                    TextBoxModify(outputTextbox, "####Error while writing " + ardFile.FileName + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
                }

                // since arduino sketches needs its core files, gather all the core files
                if (workingProject.OverrideArduinoCore)
                    GetCompilableFiles(workingProject.ArduinoCoreOverride, ardExtList, false);
                else
                    GetCompilableFiles(SettingsManagement.ArduinoCorePath, ardExtList, false);

                try
                {
                    // gather all the library files
                    ardLibList = CodePreProcess.GetAllLibraries(GetFileContents(ardFile), ardLibList);
                }
                catch (Exception ex)
                {
                    TextBoxModify(outputTextbox, "####Error while geting list of libraries, " + ex.Message, TextBoxChangeMode.PrependNewLine);
                }

                foreach (string lib in ardLibList)
                {
                    string folderPath = SettingsManagement.ArduinoLibPath + Path.DirectorySeparatorChar + lib;
                    if (Directory.Exists(folderPath))
                    {
                        GetCompilableFiles(folderPath, ardExtList, true);
                    }
                    else
                    {
                        //if (workingFileList.ContainsKey(lib + ".h"))
                        //{
                        //    ProjectFile f = workingFileList[lib + ".h"];
                        //    try
                        //    {
                        //        File.Copy(f.FileAbsPath, SettingsManagement.AppDataPath + "temp" + Path.DirectorySeparatorChar + lib + ".h", true);
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        TextBoxModify(outputTextbox, "####Error while copying " + f.FileName + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
                        //    }
                        //}
                    }
                }

                workingProject.IncludeDirList.Add(SettingsManagement.AppDataPath + "temp");

                bool objRes;

                // compile all the needed files
                foreach (ProjectFile file in ardExtList)
                {
                    objRes = Compile(file);
                    result &= objRes;
                    if (objRes)
                    {
                        avr_ar_targets += file.FileNameNoExt + ".o ";
                        objFiles += file.FileNameNoExt + ".o ";
                    }
                }

                // finally compile the sketch
                objRes = Compile(ardFile);
                result &= objRes;
                if (objRes)
                {
                    objFiles += ardFile.FileNameNoExt + ".o ";
                }
            }

            return result;
        }
Example #5
0
        static public bool ApplyTemplate(string name, AVRProject proj)
        {
            int appCnt = 0;

            XmlElement template;
            if (templates.TryGetValue(name, out template))
            {
                XmlElement docx = (XmlElement)template.CloneNode(true);
                
                List<string> alreadyInherited = new List<string>();
                alreadyInherited.Add(name);
                bool foundNew;
                do
                {
                    foundNew = false;
                    string inheritedInnerXml = "";
                    foreach (XmlElement param in docx.GetElementsByTagName("Inherit"))
                    {
                        string inheritName = param.InnerText.Trim();
                        if (alreadyInherited.Contains(inheritName) == false)
                        {
                            XmlElement inherited;
                            if (templates.TryGetValue(inheritName, out inherited))
                            {
                                inheritedInnerXml += inherited.InnerXml;
                                alreadyInherited.Add(inheritName);
                                foundNew = true;
                            }
                        }
                    }
                    docx.InnerXml += inheritedInnerXml;
                } while (foundNew);

                AVRProject.LoadTemplateCommonProperties(ref appCnt, docx, proj);

                if (appCnt >= 2)
                    proj.HasBeenConfigged = true;

                try
                {
                    foreach (XmlElement i in docx.GetElementsByTagName("CreateFile"))
                    {
                        string fname = i.GetAttribute("name");
                        if (string.IsNullOrEmpty(fname) == false)
                        {
                            try
                            {
                                ProjectFile f = new ProjectFile(Program.AbsPathFromRel(proj.DirPath, fname), proj);
                                if (proj.FileList.ContainsKey(fname.ToLowerInvariant()) == false)
                                {
                                    proj.FileList.Add(fname.ToLowerInvariant(), f);
                                    proj.ShouldReloadFiles = true;

                                    if (f.Exists == false)
                                    {
                                        Program.MakeSurePathExists(f.FileDir);
                                        File.WriteAllText(f.FileAbsPath, " ");

                                        foreach (XmlElement k in i.GetElementsByTagName("Template"))
                                        {
                                            File.WriteAllText(f.FileAbsPath, FileTemplate.CreateFile(f.FileName, proj.FileNameNoExt, k.InnerText));
                                            break;
                                        }
                                    }
                                }
                            }
                            catch { }
                        }
                    }
                }
                catch
                {
                    return false;
                }

                return true;
            }
            else
                return false;
        }
        /// <summary>
        /// Makes a copy of ProjectFile, used by the background worker of the project builder
        /// </summary>
        /// <returns>Reference to the Cloned ProjectFile</returns>
        public ProjectFile Clone()
        {
            ProjectFile newFile = new ProjectFile(fileAbsPath, this.project);
            newFile.IsOpen = this.IsOpen;
            newFile.Options = this.Options;
            newFile.ToCompile = this.ToCompile;

            newFile.Bookmarks.Clear();
            foreach (int i in this.bookMarks)
                newFile.Bookmarks.Add(i);

            newFile.FoldedLines.Clear();
            foreach (KeyValuePair<int, int> i in this.foldedLines)
                newFile.FoldedLines.Add(i.Key, i.Value);

            return newFile;
        }
        public bool Open(string path)
        {
            bool success = true;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);

                XmlElement docx = doc.DocumentElement;

                XmlElement param;
                param = (XmlElement)docx.GetElementsByTagName("DirPath")[0];
                string xDirPath = Program.CleanFilePath(param.InnerText);
                param = (XmlElement)docx.GetElementsByTagName("ClockFreq")[0];
                ClockFreq = decimal.Parse(param.InnerText);
                param = (XmlElement)docx.GetElementsByTagName("Device")[0];
                Device = param.InnerText;
                param = (XmlElement)docx.GetElementsByTagName("LinkerOpt")[0];
                LinkerOptions = param.InnerText;
                param = (XmlElement)docx.GetElementsByTagName("OtherOpt")[0];
                OtherOptions = param.InnerText;
                param = (XmlElement)docx.GetElementsByTagName("OutputDir")[0];
                OutputDir = param.InnerText;
                param = (XmlElement)docx.GetElementsByTagName("Optimization")[0];
                Optimization = param.InnerText;

                param = (XmlElement)docx.GetElementsByTagName("UseInitStack")[0];
                UseInitStack = param.InnerText.ToLower().Trim() == "true";
                param = (XmlElement)docx.GetElementsByTagName("InitStackAddr")[0];
                InitStackAddr = Convert.ToUInt32("0x" + param.InnerText, 16);

                param = (XmlElement)docx.GetElementsByTagName("PackStructs")[0];
                PackStructs = param.InnerText.ToLower().Trim() == "true";
                param = (XmlElement)docx.GetElementsByTagName("ShortEnums")[0];
                ShortEnums = param.InnerText.ToLower().Trim() == "true";
                param = (XmlElement)docx.GetElementsByTagName("UnsignedBitfields")[0];
                UnsignedBitfields = param.InnerText.ToLower().Trim() == "true";
                param = (XmlElement)docx.GetElementsByTagName("UnsignedChars")[0];
                UnsignedChars = param.InnerText.ToLower().Trim() == "true";

                param = (XmlElement)docx.GetElementsByTagName("BurnPart")[0];
                BurnPart = param.InnerText;
                param = (XmlElement)docx.GetElementsByTagName("BurnProgrammer")[0];
                BurnProgrammer = param.InnerText;
                param = (XmlElement)docx.GetElementsByTagName("BurnOptions")[0];
                BurnOptions = param.InnerText;

                IncludeDirList.Clear();
                XmlElement container = (XmlElement)docx.GetElementsByTagName("IncludeDirList")[0];
                XmlNodeList list = container.GetElementsByTagName("DirPath");
                foreach (XmlElement i in list)
                {
                    IncludeDirList.Add(i.InnerText);
                }

                LibraryDirList.Clear();
                container = (XmlElement)docx.GetElementsByTagName("IncludeDirList")[0];
                list = container.GetElementsByTagName("DirPath");
                foreach (XmlElement i in list)
                {
                    LibraryDirList.Add(i.InnerText);
                }

                LinkObjList.Clear();
                container = (XmlElement)docx.GetElementsByTagName("LinkObjList")[0];
                list = container.GetElementsByTagName("Obj");
                foreach (XmlElement i in list)
                {
                    LinkObjList.Add(i.InnerText);
                }

                LinkLibList.Clear();
                container = (XmlElement)docx.GetElementsByTagName("LinkLibList")[0];
                list = container.GetElementsByTagName("Lib");
                foreach (XmlElement i in list)
                {
                    LinkLibList.Add(i.InnerText);
                }

                MemorySegList.Clear();
                container = (XmlElement)docx.GetElementsByTagName("MemorySegList")[0];
                list = container.GetElementsByTagName("Segment");
                foreach (XmlElement i in list)
                {
                    XmlElement type = (XmlElement)i.GetElementsByTagName("Type")[0];
                    XmlElement name = (XmlElement)i.GetElementsByTagName("Name")[0];
                    XmlElement addr = (XmlElement)i.GetElementsByTagName("Addr")[0];
                    MemorySegList.Add(new MemorySegment(type.InnerText, name.InnerText, Convert.ToUInt32(addr.InnerText, 16)));
                }

                FileList.Clear();
                container = (XmlElement)docx.GetElementsByTagName("FileList")[0];
                list = container.GetElementsByTagName("File");

                string dirPath = Program.CleanFilePath(path);
                dirPath = dirPath.Substring(0, dirPath.LastIndexOf('\\'));

                List<ProjectFile> flistOld = new List<ProjectFile>();
                List<ProjectFile> flistNew = new List<ProjectFile>();

                foreach (XmlElement i in list)
                {
                    XmlElement relPath = (XmlElement)i.GetElementsByTagName("RelPath")[0];
                    XmlElement toComp = (XmlElement)i.GetElementsByTagName("ToCompile")[0];
                    XmlElement opt = (XmlElement)i.GetElementsByTagName("Options")[0];

                    string newPath = dirPath + "\\" + Program.CleanFilePath(relPath.InnerText);
                    string oldPath = xDirPath + "\\" + Program.CleanFilePath(relPath.InnerText);

                    ProjectFile newFile = new ProjectFile(newPath, dirPath.Substring(0, path.LastIndexOf('\\')));
                    flistNew.Add(newFile);

                    if (xDirPath != dirPath)
                    {
                        ProjectFile oldFile = new ProjectFile(oldPath, xDirPath);
                        flistOld.Add(oldFile);
                    }
                }

                int newCnt = 0;
                int oldCnt = 0;
                int total = flistNew.Count;

                if (flistOld.Count > 0)
                {
                    for (int i = 0; i < total && newCnt < (total + 1) / 2 && oldCnt < (total + 1) / 2; i++)
                    {
                        if (flistNew[i].Exists)
                            newCnt++;
                        if (flistOld[i].Exists)
                            oldCnt++;
                    }
                }
                else
                {
                    newCnt = total;
                }

                if (newCnt >= oldCnt)
                {
                    foreach (ProjectFile file in flistNew)
                    {
                        fileList.Add(file.FileName, file);
                    }
                    xDirPath = dirPath;
                }
                else
                {
                    foreach (ProjectFile file in flistOld)
                    {
                        fileList.Add(file.FileName, file);
                    }
                    dirPath = xDirPath;
                }
            }
            catch
            {
                success = false;
            }

            if (success)
            {
                filePath = path;
                isReady = true;
            }

            return success;
        }
        public void Run(ProjectFile file, AVRProject proj)
        {
            try
            {
                string cmd = this.cmdStr;
                if (string.IsNullOrEmpty(cmd))
                {
                    return;
                }

                Process p = new Process();
                p.StartInfo.FileName = cmd;

                if (proj != null)
                {
                    if (proj.IsReady)
                    {
                        p.StartInfo.WorkingDirectory = proj.DirPath;
                    }
                }

                string args = this.argsStr;

                if (string.IsNullOrEmpty(args) == false)
                {
                    if (proj != null)
                    {
                        if (proj.IsReady)
                        {
                            args = args.Replace("%PROJNAME%", proj.FileNameNoExt);
                            args = args.Replace("%PROJDIR%", proj.DirPath);
                            args = args.Replace("%PROJOUTFOLDER%", proj.OutputDir);
                            args = args.Replace("%PROJCHIP%", proj.Device);

                            if (file != null)
                            {
                                args = args.Replace("%FILENAMENOEXT%", file.FileNameNoExt);
                                args = args.Replace("%FILEEXT%", file.FileExt);
                                args = args.Replace("%FILEDIR%", file.FileDir);
                            }
                        }
                    }

                    ProjectBuilder.SetEnviroVarsForProc(p.StartInfo);
                    p.StartInfo.Arguments = args;
                }

                string dir = this.dirStr;
                if (string.IsNullOrEmpty(dir) == false)
                {
                    if (proj != null)
                    {
                        if (proj.IsReady)
                        {
                            dir = dir.Replace("%PROJDIR%", proj.DirPath);
                            dir = dir.Replace("%PROJOUTFOLDER%", proj.OutputDir);

                            if (file != null)
                            {
                                dir = dir.Replace("%FILEDIR%", file.FileDir);
                            }
                        }
                    }

                    p.StartInfo.WorkingDirectory = dir;
                }

                if (p.Start())
                {
                    //
                }
                else
                {
                    MessageBox.Show(String.Format("Process '{0} {1}' failed to start.", cmd, args));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error during execution: " + ex.Message);
            }
        }
Example #9
0
        private void btnCreate_Click(object sender, EventArgs e)
        {
            string f = txtFileName.Text.Trim();

            if (string.IsNullOrEmpty(f))
            {
                MessageBox.Show("File name must not be blank");
                return;
            }

            string fileName;

            if (f.EndsWith("."))
            {
                fileName = f + this.SelectedExtension.TrimStart('.');
            }
            else if (f.Contains("."))
            {
                fileName = f;
            }
            else
            {
                fileName = f + "." + this.SelectedExtension.TrimStart('.');
            }

            if (
                fileName.Contains(" ") ||
                fileName.Contains("\t") ||
                fileName.Contains("\r") ||
                fileName.Contains("\n") ||
                fileName.Contains("\0") ||
                fileName.Contains("\\") ||
                fileName.Contains("/")
                )
            {
                MessageBox.Show("Invalid Character in File Name");
                return;
            }

            foreach (char c in Path.GetInvalidFileNameChars())
            {
                if (fileName.Contains(char.ToString(c)))
                {
                    MessageBox.Show("Invalid Character '" + c + "' in File Name");
                    return;
                }
            }

            string fileAbsPath = txtDirLoc.Text + fileName;

            foreach (char c in Path.GetInvalidPathChars())
            {
                if (fileAbsPath.Contains(char.ToString(c)))
                {
                    MessageBox.Show("Invalid Character '" + c + "' in File Path");
                    return;
                }
            }

            string fileNameL = fileName.ToLowerInvariant();

            if (project.FileList.ContainsKey(fileNameL))
            {
                if (project.FileList[fileNameL].Exists)
                {
                    MessageBox.Show("File already exists in the project");
                    return;
                }
            }
            else
            {
                project.FileList.Add(fileNameL, new ProjectFile(fileAbsPath, project));
            }

            if (project.FileList[fileNameL].Exists == false)
            {
                if (((string)dropTemplates.Items[dropTemplates.SelectedIndex]) != "none")
                {
                    try
                    {
                        File.WriteAllText(fileAbsPath, FileTemplate.CreateFile(fileName, project.FileNameNoExt, ((string)dropTemplates.Items[dropTemplates.SelectedIndex]) + ".txt"));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error writing file from template, " + ex.Message);
                    }
                }
                else
                {
                    try
                    {
                        File.WriteAllText(fileAbsPath, "");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error creating file, " + ex.Message);
                    }
                }
            }

            createdFile = project.FileList[fileNameL];

            if (project.FileList.Count == 1)
            {
                project.FileList[fileNameL].IsOpen = true;
            }

            if (project.Save() == SaveResult.Failed)
            {
                MessageBox.Show("Error saving project");
            }

            SettingsManagement.LastFileExt = createdFile.FileExt;

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Example #10
0
        private bool Compile(ProjectFile file)
        {
            string outputAbsPath = workingProject.DirPath + "\\" + workingProject.OutputDir;

            if (Program.MakeSurePathExists(outputAbsPath) == false)
            {
                return(false);
            }

            string objectFileAbsPath = outputAbsPath + "\\" + file.FileNameNoExt + ".o";

            if (File.Exists(objectFileAbsPath))
            {
                try
                {
                    File.Delete(objectFileAbsPath);
                }
                catch (Exception ex)
                {
                    TextBoxModify(myOutput, "Error: object file could not be deleted at " + objectFileAbsPath + "\r\n" + ex.ToString(), TextBoxChangeMode.AppendNewLine);
                }
            }

            string args = "";

            foreach (string path in workingProject.IncludeDirList)
            {
                if (string.IsNullOrEmpty(path) == false)
                {
                    args += "-I\"" + path + "\" ";
                }
            }
            //args += "-I\"" + file.FileDir + "\" ";

            string checklist = "";

            if (myProject.PackStructs)
            {
                checklist += "-fpack-struct ";
            }

            if (myProject.ShortEnums)
            {
                checklist += "-fshort-enums ";
            }

            if (myProject.UnsignedChars)
            {
                checklist += "-funsigned-char ";
            }

            if (myProject.UnsignedBitfields)
            {
                checklist += "-funsigned-bitfields ";
            }

            string asmflags = "";

            if (file.FileExt == "s")
            {
                asmflags += "-x assembler-with-cpp -Wa,-gdwarf2";
            }

            args += String.Format(" -mmcu={0} -Wall -gdwarf-2 -std=gnu99 -DF_CPU={1}UL {2} {3} {4} -MD -MP -MT {5}.o {6} -c {7} \"{8}\"",
                                  workingProject.Device,
                                  Math.Round(myProject.ClockFreq),
                                  workingProject.Optimization,
                                  checklist,
                                  workingProject.OtherOptions,
                                  file.FileNameNoExt,
                                  asmflags,
                                  file.Options,
                                  file.FileAbsPath.Replace('\\', '/')
                                  );

            TextBoxModify(myOutput, "Execute: avr-gcc " + args, TextBoxChangeMode.AppendNewLine);

            ProcessStartInfo psi = new ProcessStartInfo("avr-gcc", args);

            psi.WorkingDirectory       = outputAbsPath + "\\";
            psi.UseShellExecute        = false;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput  = true;
            Process avrgcc = new Process();

            avrgcc.StartInfo = psi;
            try
            {
                if (avrgcc.Start())
                {
                    StreamReader stderr = avrgcc.StandardError;
                    ReadErrAndWarnings(stderr);
                    StreamReader stdout = avrgcc.StandardOutput;
                    ReadErrAndWarnings(stdout);
                    avrgcc.WaitForExit(10000);
                }
                else
                {
                    TextBoxModify(myOutput, "Error: unable to start avr-gcc", TextBoxChangeMode.AppendNewLine);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                TextBoxModify(myOutput, "Error: unable to start avr-gcc\r\n" + ex.ToString(), TextBoxChangeMode.AppendNewLine);
                return(false);
            }

            if (File.Exists(objectFileAbsPath))
            {
                return(true);
            }
            else
            {
                TextBoxModify(myOutput, "Error: object file not created at " + objectFileAbsPath, TextBoxChangeMode.AppendNewLine);
                return(false);
            }
        }
        private bool Compile(ProjectFile file)
        {
            string outputAbsPath = workingProject.DirPath + "\\" + workingProject.OutputDir;

            if (Program.MakeSurePathExists(outputAbsPath) == false)
                return false;

            string objectFileAbsPath = outputAbsPath + "\\" + file.FileNameNoExt + ".o";

            if (File.Exists(objectFileAbsPath))
            {
                try
                {
                    File.Delete(objectFileAbsPath);
                }
                catch (Exception ex)
                {
                    TextBoxModify(myOutput, "Error: object file could not be deleted at " + objectFileAbsPath + "\r\n" + ex.ToString(), TextBoxChangeMode.AppendNewLine);
                }
            }

            string args = "";
            foreach (string path in workingProject.IncludeDirList)
            {
                if(string.IsNullOrEmpty(path) == false)
                    args += "-I\"" + path + "\" ";
            }
            //args += "-I\"" + file.FileDir + "\" ";

            string checklist = "";

            if (myProject.PackStructs)
                checklist += "-fpack-struct ";

            if (myProject.ShortEnums)
                checklist += "-fshort-enums ";

            if (myProject.UnsignedChars)
                checklist += "-funsigned-char ";

            if (myProject.UnsignedBitfields)
                checklist += "-funsigned-bitfields ";

            string asmflags = "";

            if (file.FileExt == "s")
                asmflags += "-x assembler-with-cpp -Wa,-gdwarf2";

            args += String.Format(" -mmcu={0} -Wall -gdwarf-2 -std=gnu99 -DF_CPU={1}UL {2} {3} {4} -MD -MP -MT {5}.o {6} -c {7} \"{8}\"",
                workingProject.Device,
                Math.Round(myProject.ClockFreq),
                workingProject.Optimization,
                checklist,
                workingProject.OtherOptions,
                file.FileNameNoExt,
                asmflags,
                file.Options,
                file.FileAbsPath.Replace('\\', '/')
            );

            TextBoxModify(myOutput, "Execute: avr-gcc " + args, TextBoxChangeMode.AppendNewLine);

            ProcessStartInfo psi = new ProcessStartInfo("avr-gcc", args);
            psi.WorkingDirectory = outputAbsPath + "\\";
            psi.UseShellExecute = false;
            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            Process avrgcc = new Process();
            avrgcc.StartInfo = psi;
            try
            {
                if (avrgcc.Start())
                {
                    StreamReader stderr = avrgcc.StandardError;
                    ReadErrAndWarnings(stderr);
                    StreamReader stdout = avrgcc.StandardOutput;
                    ReadErrAndWarnings(stdout);
                    avrgcc.WaitForExit(10000);
                }
                else
                {
                    TextBoxModify(myOutput, "Error: unable to start avr-gcc", TextBoxChangeMode.AppendNewLine);
                    return false;
                }
            }
            catch (Exception ex)
            {
                TextBoxModify(myOutput, "Error: unable to start avr-gcc\r\n" + ex.ToString(), TextBoxChangeMode.AppendNewLine);
                return false;
            }

            if (File.Exists(objectFileAbsPath))
            {
                return true;
            }
            else
            {
                TextBoxModify(myOutput, "Error: object file not created at " + objectFileAbsPath, TextBoxChangeMode.AppendNewLine);
                return false;
            }
        }
Example #12
0
        public SaveResult AddFile(out ProjectFile file, string filePath)
        {
            string fn = Path.GetFileName(filePath);
            string ext = Path.GetExtension(fn).ToLowerInvariant();

            if (project.FileList.TryGetValue(fn.ToLowerInvariant(), out file))
            {
                if (file.FileAbsPath != filePath && file.Exists)
                {
                    // name conflict, do not allow
                    MessageBox.Show("Error, Cannot Add File " + file.FileName + " Due To Name Conflict");
                    return SaveResult.Failed;
                }
                else
                {
                    // added file already in list, maybe it was missing, so refresh the list to update icons
                    PopulateList();
                    return SaveResult.Cancelled;
                }
            }
            else
            {
                if (ext == ".c" || ext == ".cpp" || ext == ".cxx" || ext == ".s" || ext == ".h" || ext == ".hpp")
                {
                    // check for space if it's a source or header file, we don't care about the other files
                    if (fn.Contains(" "))
                    {
                        MessageBox.Show("Error, File Name May Not Contain Spaces");
                        return SaveResult.Failed;
                    }
                }

                file = new ProjectFile(filePath, this.project);

                if (file.Exists == false)
                {
                    try
                    {
                        StreamWriter newFile = new StreamWriter(file.FileAbsPath);

                        if (file.FileExt == "h" || file.FileExt == "hpp")
                        {
                            newFile.WriteLine(FileTemplate.CreateFile(file.FileName, project.FileNameNoExt, "defaultheader.txt"));
                        }
                        else if (file.FileExt == "c" || file.FileExt == "cpp")
                        {
                            newFile.WriteLine(FileTemplate.CreateFile(file.FileName, project.FileNameNoExt, "defaultcode.txt"));
                        }
                        else
                            newFile.WriteLine(FileTemplate.CreateFile(file.FileName, project.FileNameNoExt, "default_" + file.FileExt + ".txt"));

                        newFile.Close();
                    }
                    catch (Exception ex)
                    {
                        ErrorReportWindow.Show(ex, "Error Creating New File " + file.FileName);

                    }
                }

                project.FileList.Add(fn.ToLowerInvariant(), file);

                if (project.Save() == SaveResult.Failed)
                {
                    MessageBox.Show("Error saving project");
                }

                PopulateList();
                return SaveResult.Successful;
            }
        }
Example #13
0
        public SaveResult AddExistingFile(out ProjectFile file)
        {
            file = null;

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title = "Add Existing File(s)";

            ofd.InitialDirectory = project.DirPath;

            string filter = "";
            filter += "Code/Header Files (*.c;*.cpp;*.S;*.pde;*.h;*.hpp)|*.c;*.cpp;*.S;*.pde;*.h;*.hpp" + "|";
            filter += GetSaveFileFilters();
            ofd.Filter = filter;
            ofd.FilterIndex = 0;

            ofd.Multiselect = true;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                SaveResult result = SaveResult.Successful;
                foreach (string fileName in ofd.FileNames)
                {
                    SaveResult addFileResult = AddFile(out file, fileName);
                    if (addFileResult != SaveResult.Successful)
                    {
                        result = addFileResult;
                    }
                }
                return result;
            }

            return SaveResult.Cancelled;
        }
Example #14
0
        public SaveResult AddNewFile(out ProjectFile file)
        {
            file = null;

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title = "Add New File";

            sfd.InitialDirectory = project.DirPath;

            string filter = GetSaveFileFilters();
            sfd.Filter = filter;
            sfd.FilterIndex = SettingsManagement.LastFileTypeFilter;

            sfd.AddExtension = true;

            sfd.OverwritePrompt = true;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                SettingsManagement.LastFileTypeFilter = sfd.FilterIndex;
                return AddFile(out file, sfd.FileName);
            }

            return SaveResult.Cancelled;
        }
 private void btnFindFile_Click(object sender, EventArgs e)
 {
     OpenFileDialog ofd = new OpenFileDialog();
     ofd.Filter = "C Code (*.c)|*.c|Header File (*.h)|*.h|Assembly Code (*.S)|*.S";
     if (ofd.ShowDialog() == DialogResult.OK)
     {
         if (ofd.SafeFileName.Contains(' ') == false)
         {
             ProjectFile pf = new ProjectFile(ofd.FileName, myProject.DirPath);
             if (myProject.FileList.TryGetValue(pf.FileName, out pf) == false)
             {
                 pf = new ProjectFile(ofd.FileName, myProject.DirPath);
                 myProject.FileList.Add(pf.FileName, pf);
                 ((frmProjIDE)(this.ParentForm)).RefreshFileTree();
             }
             else if (pf.Exists == false)
             {
                 pf = new ProjectFile(ofd.FileName, myProject.DirPath);
                 myProject.FileList.Add(pf.FileName, pf);
                 ((frmProjIDE)(this.ParentForm)).RefreshFileTree();
             }
             else
             {
                 MessageBox.Show("Please No Duplicate File Names, " + ofd.SafeFileName + " is already used.");
             }
         }
         else
         {
             MessageBox.Show("Please No Spaces in File Name");
         }
     }
 }
        public FileEditorTab(ProjectFile myFile, TreeNode treeNode)
        {
            this.myFile = myFile;
            this.myNode = treeNode;

            myTabPage = new TabPage(this.myFile.FileName);

            myScint = new Scintilla();
            myScint.Dock = DockStyle.Fill;
            myScint.ConfigurationManager.Language = "cs";
            myScint.Lexing.SetKeywords(0, "if else for do while	switch case default goto break continue return sizeof free malloc calloc PSTR ISR SIGNAL");
            myScint.Lexing.SetKeywords(1, "void inline extern signed unsigned typedef union struct enum volatile static const byte char short int long word dword float double bool bit bitfield byte uchar ushort uint ulong uword uint8_t uint16_t uint32_t uint64_t int8_t int16_t int32_t int64_t");

            for (int i = 0; i < 256; i++)
            {
                try
                {
                    if (myScint.Styles[i].ForeColor == Color.Teal)
                    {
                        myScint.Styles[i].ForeColor = Color.Purple;
                    }
                    if (myScint.Styles[i].ForeColor == Color.Orange)
                    {
                        myScint.Styles[i].ForeColor = Color.DarkBlue;
                    }
                    if (myScint.Styles[i].ForeColor == Color.DarkGoldenrod)
                    {
                        myScint.Styles[i].ForeColor = Color.BlueViolet;
                    }
                }
                catch
                {
                    break;
                }
            }

            myScint.Folding.IsEnabled = true;
            myScint.Folding.MarkerScheme = FoldMarkerScheme.BoxPlusMinus;

            myScint.Margins[0].Width = 20;
            myScint.Margins[1].Width = 10;
            myScint.Margins[2].Width = 10;

            myScint.IsBraceMatching = true;
            myScint.MatchBraces = true;

            myScint.Scrolling.ScrollBars = ScrollBars.Vertical;

            myScint.LineWrap.Mode = WrapMode.Word;

            myScint.Indentation.SmartIndentType = SmartIndent.CPP;
            myScint.Indentation.TabIndents = true;
            myScint.Indentation.UseTabs = true;
            myScint.Indentation.IndentWidth = 4;
            myScint.Indentation.ShowGuides = true;

            myScint.Modified = false;
            myScint.TextChanged += new EventHandler(MakeChange);

            Load();

            myTabPage.Controls.Add(myScint);

            externChangeWatcher.Filter = myFile.FileName;
            externChangeWatcher.Path = myFile.FileDir + "\\";
            externChangeWatcher.IncludeSubdirectories = false;
            externChangeWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.DirectoryName;

            externChangeWatcher.Renamed += new RenamedEventHandler(externChangeWatcher_Renamed);
            externChangeWatcher.Deleted += new FileSystemEventHandler(externChangeWatcher_Deleted);
            externChangeWatcher.Changed += new FileSystemEventHandler(externChangeWatcher_Changed);
        }
Example #17
0
        public void Run(ProjectFile file, AVRProject proj)
        {
            try
            {
                string cmd = this.cmdStr;
                if (string.IsNullOrEmpty(cmd))
                    return;

                Process p = new Process();
                p.StartInfo.FileName = cmd;

                if (proj != null)
                {
                    if (proj.IsReady)
                    {
                        p.StartInfo.WorkingDirectory = proj.DirPath;
                    }
                }

                string args = this.argsStr;

                if (string.IsNullOrEmpty(args) == false)
                {
                    if (proj != null)
                    {
                        if (proj.IsReady)
                        {
                            args = args.Replace("%PROJNAME%", proj.FileNameNoExt);
                            args = args.Replace("%PROJDIR%", proj.DirPath);
                            args = args.Replace("%PROJOUTFOLDER%", proj.OutputDir);
                            args = args.Replace("%PROJCHIP%", proj.Device);

                            if (file != null)
                            {
                                args = args.Replace("%FILENAMENOEXT%", file.FileNameNoExt);
                                args = args.Replace("%FILEEXT%", file.FileExt);
                                args = args.Replace("%FILEDIR%", file.FileDir);
                            }
                        }
                    }

                    ProjectBuilder.SetEnviroVarsForProc(p.StartInfo);
                    p.StartInfo.Arguments = args;
                }

                string dir = this.dirStr;
                if (string.IsNullOrEmpty(dir) == false)
                {
                    if (proj != null)
                    {
                        if (proj.IsReady)
                        {
                            dir = dir.Replace("%PROJDIR%", proj.DirPath);
                            dir = dir.Replace("%PROJOUTFOLDER%", proj.OutputDir);

                            if (file != null)
                            {
                                dir = dir.Replace("%FILEDIR%", file.FileDir);
                            }
                        }
                    }

                    p.StartInfo.WorkingDirectory = dir;
                }

                if (p.Start())
                {
                    //
                }
                else
                {
                    MessageBox.Show(String.Format("Process '{0} {1}' failed to start.", cmd, args));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error during execution: " + ex.Message);
            }
            
        }
Example #18
0
 public static List<string> GetListForFile(ProjectFile file)
 {
     if (allResReady.WaitOne(500))
     {
         if (allResults.ContainsKey(file))
             return allResults[file];
         else
             return new List<string>();
     }
     else
         return new List<string>();
 }
Example #19
0
        public static void FeedFileContent(ProjectFile file)
        {
            if (SettingsManagement.AutocompleteEnable == false)
                return;

            try
            {
                FeedFileContent(file, File.ReadAllText(file.FileAbsPath));
            }
            catch { }
        }
        public bool ImportAPS(string path)
        {
            bool success = true;

            try
            {
                path = Program.CleanFilePath(path);
                string pathDir = path.Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar));

                dirPath = pathDir;

                XmlDocument doc = new XmlDocument();
                doc.Load(path);

                XmlElement docx = doc.DocumentElement;

                if (docx.GetElementsByTagName("AVRGCCPLUGIN").Count > 0)
                {
                    foreach (XmlElement param in docx.GetElementsByTagName("PART"))
                    {
                        Device = param.InnerText;
                        BurnPart = Device;
                    }

                    IncludeDirList.Clear();
                    foreach (XmlElement container in docx.GetElementsByTagName("INCDIRS"))
                    {
                        foreach (XmlElement i in container.GetElementsByTagName("INCLUDE"))
                        {
                            IncludeDirList.Add(Program.AbsPathFromRel(pathDir, i.InnerText));
                        }
                    }

                    LibraryDirList.Clear();
                    foreach (XmlElement container in docx.GetElementsByTagName("LIBDIRS"))
                    {
                        foreach (XmlElement i in container.GetElementsByTagName("LIBDIR"))
                        {
                            LibraryDirList.Add(Program.AbsPathFromRel(pathDir, i.InnerText));
                        }
                    }

                    LinkObjList.Clear();
                    foreach (XmlElement container in docx.GetElementsByTagName("LINKOBJECTS"))
                    {
                        foreach (XmlElement i in container.GetElementsByTagName("LINKOBJECT"))
                        {
                            LinkObjList.Add(Program.AbsPathFromRel(pathDir, i.InnerText));
                        }
                    }

                    LinkLibList.Clear();
                    foreach (XmlElement container in docx.GetElementsByTagName("LIBS"))
                    {
                        foreach (XmlElement i in container.GetElementsByTagName("LIB"))
                        {
                            LinkLibList.Add(i.InnerText);
                        }
                    }

                    MemorySegList.Clear();
                    foreach (XmlElement container in docx.GetElementsByTagName("SEGMENTS"))
                    {
                        foreach (XmlElement i in container.GetElementsByTagName("SEGMENT"))
                        {
                            if (i.HasChildNodes)
                            {
                                try
                                {
                                    XmlElement type = (XmlElement)i.GetElementsByTagName("SEGMENT")[0];
                                    XmlElement name = (XmlElement)i.GetElementsByTagName("NAME")[0];
                                    XmlElement addr = (XmlElement)i.GetElementsByTagName("ADDRESS")[0];
                                    uint address;
                                    if (addr.InnerText.ToLowerInvariant().StartsWith("0x"))
                                    {
                                        address = Convert.ToUInt32(addr.InnerText, 16);
                                    }
                                    else
                                    {
                                        address = Convert.ToUInt32("0x" + addr.InnerText, 16);
                                    }

                                    string nameStr = name.InnerText.Trim();
                                    string typeStr = type.InnerText.Trim();

                                    if (string.IsNullOrEmpty(nameStr) == false && string.IsNullOrEmpty(typeStr) == false)
                                    {
                                        MemorySegment seg = new MemorySegment(typeStr, nameStr, address);

                                        if (MemorySegList.ContainsKey(nameStr) == false)
                                            MemorySegList.Add(nameStr, seg);
                                    }
                                }
                                catch { }
                            }
                        }
                    }

                    if (docx.GetElementsByTagName("OPTIONSFORALL").Count > 0)
                    {
                        UnsignedChars = false;
                        UnsignedBitfields = false;
                        PackStructs = false;
                        ShortEnums = false;
                        OtherOptions = "";
                        XmlElement param = (XmlElement)docx.GetElementsByTagName("OPTIONSFORALL")[0];
                        string OPTIONSFORALL = param.InnerText.Trim();
                        string[] opts = OPTIONSFORALL.Split(new char[] { ' ', '\t', '\r', '\n', });
                        foreach (string o in opts)
                        {
                            if (string.IsNullOrEmpty(o) == false)
                            {
                                if (o == "-funsigned-char")
                                {
                                    UnsignedChars = true;
                                }
                                else if (o == "-funsigned-bitfields")
                                {
                                    UnsignedBitfields = true;
                                }
                                else if (o == "-fpack-struct")
                                {
                                    PackStructs = true;
                                }
                                else if (o == "-fshort-enums")
                                {
                                    ShortEnums = true;
                                }
                                else if (o == "-ffunction-sections")
                                {
                                    FunctionSections = true;
                                }
                                else if (o == "-fdata-sections")
                                {
                                    DataSections = true;
                                }
                                else if (o.StartsWith("-DF_CPU="))
                                {
                                    string oo = o.Substring("-DF_CPU=".Length).ToUpperInvariant();
                                    oo = oo.TrimEnd('L').TrimEnd('L');
                                    oo = oo.TrimEnd('I');
                                    oo = oo.TrimEnd('S');
                                    oo = oo.TrimEnd('C');
                                    oo = oo.TrimEnd('F');
                                    oo = oo.TrimEnd('D');
                                    oo = oo.TrimEnd('U');
                                    if (decimal.TryParse(oo, out clkFreq) == false)
                                    {
                                        ClockFreq = 8000000;
                                    }
                                }
                                else if (o.StartsWith("-O"))
                                {
                                    Optimization = o;
                                }
                                else
                                {
                                    OtherOptions += " " + o;
                                }
                            }
                        }
                    }

                    foreach (XmlElement param in docx.GetElementsByTagName("LINKEROPTIONS"))
                    {
                        UseInitStack = false;
                        string[] linkerOptList = param.InnerText.Split(new char[] { ' ', '\t', '\r', '\n', });
                        foreach (string o in linkerOptList)
                        {
                            if (o.StartsWith("-Wl,--defsym=__stack="))
                            {
                                UseInitStack = true;
                                if (uint.TryParse(o.Substring("-Wl,--defsym=__stack=".Length), out initStackAddr) == false)
                                    initStackAddr = uint.MaxValue;
                            }
                            else
                            {
                                LinkerOptions += " " + param.InnerText;
                            }
                        }
                    }

                    foreach (XmlElement param in docx.GetElementsByTagName("OUTPUTDIR"))
                    {
                        OutputDir = Program.CleanFilePath(param.InnerText);
                    }
                }

                foreach (XmlElement param in docx.GetElementsByTagName("SaveFolder"))
                {
                    dirPath = Program.CleanFilePath(param.InnerText);
                }

                fileList.Clear();
                if (docx.GetElementsByTagName("ProjectFiles").Count > 0)
                {
                    XmlElement xProjFilesContainer = (XmlElement)docx.GetElementsByTagName("ProjectFiles")[0];

                    foreach (XmlElement i in xProjFilesContainer.GetElementsByTagName("Name"))
                    {
                        ProjectFile file = new ProjectFile(i.InnerText, this);
                        fileList.Add(file.FileName.ToLowerInvariant(), file);
                    }
                }
                else if (docx.GetElementsByTagName("AVRGCCPLUGIN").Count > 0)
                {
                    XmlElement pluginContainer = (XmlElement)docx.GetElementsByTagName("AVRGCCPLUGIN")[0];

                    foreach (XmlElement filesContainer in pluginContainer.GetElementsByTagName("FILES"))
                    {
                        foreach (XmlElement i in filesContainer.ChildNodes)
                        {
                            ProjectFile file = new ProjectFile(Program.AbsPathFromRel(dirPath, i.InnerText), this);
                            fileList.Add(file.FileName.ToLowerInvariant(), file);
                        }
                    }
                }

                foreach (XmlElement pluginContainer in docx.GetElementsByTagName("AVRGCCPLUGIN"))
                {
                    foreach (XmlElement optionsContainer in pluginContainer.GetElementsByTagName("OPTIONS"))
                    {
                        foreach (XmlElement i in optionsContainer.GetElementsByTagName("OPTION"))
                        {
                            if (i.GetElementsByTagName("FILE").Count > 0 && i.GetElementsByTagName("OPTIONLIST").Count > 0)
                            {
                                XmlElement param = (XmlElement)i.GetElementsByTagName("FILE")[0];
                                string fileName = Program.CleanFilePath(param.InnerText);
                                param = (XmlElement)i.GetElementsByTagName("OPTIONLIST")[0];
                                string optionsForFile = param.InnerText;

                                ProjectFile file;
                                if (fileList.TryGetValue(fileName.ToLowerInvariant(), out file))
                                {
                                    file.Options = optionsForFile;
                                }
                            }
                        }
                    }
                }

                APSXmlElementList.Clear();
                string[] otherXEles = new string[] {"AVRSimulator", "DEBUG_TARGET", "Debugger", "IOView", "Events", "Trace", };
                foreach (string xEleName in otherXEles)
                {
                    if (docx.GetElementsByTagName(xEleName).Count > 0)
                    {
                        APSXmlElementList.Add((XmlElement)docx.GetElementsByTagName(xEleName)[0]);
                    }
                }

            }
            catch (XmlException ex)
            {
                MessageBox.Show("Error in APS File: " + ex.Message);
                success = false;
            }
            catch { success = false; }

            if (success)
            {
                isReady = true;
            }

            return success;
        }
Example #21
0
        public static void FeedFileContent(ProjectFile file, string content)
        {
            if (SettingsManagement.AutocompleteEnable == false)
                return;

            if (bgScanner.IsAlive)
                readyForFeed.WaitOne();

            content = CodePreProcess.StripComments(content);

            if (fileContents.ContainsKey(file))
                fileContents[file] = content;
            else
                fileContents.Add(file, content);

            DoMoreWork();
        }
        public bool Open(string path)
        {
            if (string.IsNullOrEmpty(path))
                return false;

            path = Program.CleanFilePath(path);

            if (File.Exists(path) == false)
                return false;

            //LoadWaitWindow lww = new LoadWaitWindow();
            //lww.Show();

            bool success = true;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);

                XmlElement docx = doc.DocumentElement;

                string xDirPath = path.Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar));
                foreach (XmlElement param in docx.GetElementsByTagName("DirPath"))
                {
                    xDirPath = Program.CleanFilePath(param.InnerText);
                }

                foreach (XmlElement param in docx.GetElementsByTagName("HasBeenConfigged"))
                {
                    HasBeenConfigged = Program.StringToBool(param);
                }

                foreach (XmlElement param in docx.GetElementsByTagName("OutputDir"))
                {
                    OutputDir = param.InnerText;
                }

                LibraryDirList.Clear();
                LinkLibList.Clear();
                IncludeDirList.Clear();
                LinkObjList.Clear();
                MemorySegList.Clear();

                int appCnt = 0;

                LoadTemplateCommonProperties(ref appCnt, docx, this);

                foreach (XmlElement param in docx.GetElementsByTagName("BurnPort"))
                {
                    BurnPort = param.InnerText;
                }

                foreach (XmlElement param in docx.GetElementsByTagName("LastFile"))
                {
                    LastFile = param.InnerText;
                }

                FileList.Clear();
                foreach (XmlElement container in docx.GetElementsByTagName("FileList"))
                {
                    string dirPath = Program.CleanFilePath(path);
                    dirPath = dirPath.Substring(0, dirPath.LastIndexOf('\\'));

                    List<ProjectFile> flistOld = new List<ProjectFile>();
                    List<ProjectFile> flistNew = new List<ProjectFile>();

                    foreach (XmlElement i in container.GetElementsByTagName("File"))
                    {
                        foreach (XmlElement relPath in i.GetElementsByTagName("RelPath"))
                        {
                            string newPath = dirPath + Path.DirectorySeparatorChar + Program.CleanFilePath(relPath.InnerText);
                            string oldPath = xDirPath + Path.DirectorySeparatorChar + Program.CleanFilePath(relPath.InnerText);

                            ProjectFile newFile = new ProjectFile(newPath, this);

                            foreach (XmlElement toComp in i.GetElementsByTagName("ToCompile"))
                            {
                                newFile.ToCompile = Program.StringToBool(toComp);
                            }

                            foreach (XmlElement opt in i.GetElementsByTagName("Options"))
                            {
                                newFile.Options = opt.InnerText.Trim();
                            }

                            foreach (XmlElement wasOpen in i.GetElementsByTagName("WasOpen"))
                            {
                                newFile.IsOpen = Program.StringToBool(wasOpen);
                            }

                            foreach (XmlElement cursorPos in i.GetElementsByTagName("CursorPos"))
                            {
                                int curPos = 0;
                                if (int.TryParse(cursorPos.InnerText, out curPos))
                                    newFile.CursorPos = curPos;
                            }

                            newFile.Bookmarks.Clear();
                            foreach (XmlElement bookMarks in i.GetElementsByTagName("Bookmarks"))
                            {
                                string tmp = bookMarks.InnerText;
                                string[] bkmkListStr = tmp.Split(new char[] { ',', ' ', '\t', '\n', '\r', '\0', });
                                foreach (string s in bkmkListStr)
                                {
                                    if (string.IsNullOrEmpty(s) == false)
                                    {
                                        int lineNum = -1;
                                        if (int.TryParse(s, out lineNum))
                                            newFile.Bookmarks.Add(lineNum);
                                    }
                                }
                            }

                            newFile.FoldedLines.Clear();
                            foreach (XmlElement foldedLines in i.GetElementsByTagName("FoldedLines"))
                            {
                                try
                                {
                                    string tmp = foldedLines.InnerText;
                                    string[] foldListStr = tmp.Split(new char[] { ',', ' ', '\t', '\n', '\r', '\0', });
                                    foreach (string s in foldListStr)
                                    {
                                        if (string.IsNullOrEmpty(s) == false)
                                        {
                                            string[] kv = s.Split(':');

                                            int lineNum = -1;
                                            int foldLvl = -1;
                                            if (int.TryParse(kv[0], out lineNum) && int.TryParse(kv[1], out foldLvl))
                                                newFile.FoldedLines.Add(lineNum, foldLvl);
                                        }
                                    }
                                }
                                catch { }
                            }

                            flistNew.Add(newFile);

                            if (xDirPath != dirPath)
                            {
                                ProjectFile oldFile = new ProjectFile(oldPath, this);

                                oldFile.ToCompile = newFile.ToCompile;
                                oldFile.Options = newFile.Options;
                                oldFile.IsOpen = newFile.IsOpen;
                                oldFile.CursorPos = newFile.CursorPos;

                                oldFile.Bookmarks.Clear();
                                foreach (int j in newFile.Bookmarks)
                                    oldFile.Bookmarks.Add(j);

                                oldFile.FoldedLines.Clear();
                                foreach (KeyValuePair<int, int> j in newFile.FoldedLines)
                                    oldFile.FoldedLines.Add(j.Key, j.Value);

                                flistOld.Add(oldFile);
                            }

                            break;
                        }
                    }

                    int newCnt = 0;
                    int oldCnt = 0;
                    int total = flistNew.Count;

                    if (flistOld.Count > 0)
                    {
                        for (int i = 0; i < total && newCnt < (total + 1) / 2 && oldCnt < (total + 1) / 2; i++)
                        {
                            newCnt++;
                            if (flistNew[i].Exists)
                                if (flistOld[i].Exists)
                                    oldCnt++;
                        }
                    }
                    else
                    {
                        newCnt = total;
                    }

                    if (newCnt >= oldCnt)
                    {
                        foreach (ProjectFile file in flistNew)
                        {
                            if (fileList.ContainsKey(file.FileName.ToLowerInvariant()) == false)
                                fileList.Add(file.FileName.ToLowerInvariant(), file);
                        }
                        xDirPath = dirPath;
                    }
                    else
                    {
                        foreach (ProjectFile file in flistOld)
                        {
                            if (fileList.ContainsKey(file.FileName.ToLowerInvariant()) == false)
                                fileList.Add(file.FileName.ToLowerInvariant(), file);
                        }
                        dirPath = xDirPath;
                    }
                }

                APSXmlElementList.Clear();
                foreach (XmlElement container in docx.GetElementsByTagName("AVRStudioXMLStuff"))
                {
                    foreach (XmlElement i in container.ChildNodes)
                    {
                        APSXmlElementList.Add(i);
                    }
                }
            }
            catch (XmlException ex)
            {
                MessageBox.Show("Error in Project File: " + ex.Message);
                success = false;
            }
            catch { success = false; }

            if (success)
            {
                filePath = path;
                isReady = true;
                dirPath = filePath.Substring(0, filePath.LastIndexOf(Path.DirectorySeparatorChar));

                if (string.IsNullOrEmpty(SettingsManagement.FavFolder))
                {
                    SettingsManagement.FavFolder = dirPath.Substring(0, dirPath.LastIndexOf(Path.DirectorySeparatorChar));
                }
            }

            //lww.Close();

            return success;
        }
Example #23
0
        public static List<string> GetKeywordsUpTo(ProjectFile file, string content)
        {
            if (allResReady.WaitOne(1000) == false)
                return new List<string>();

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

            if (allResults.ContainsKey(file))
                finalRes.AddRange(allResults[file]);

            int contentLen = content.Length;
            content = Environment.NewLine + content + Environment.NewLine;

            string noStringContent = "";
            bool inStreamComment = false;
            bool inLineComment = false;
            bool inString = false;
            bool inChar = false;

            content = Environment.NewLine + content;
            int originalLength = content.Length;
            content += Environment.NewLine;

            for (int i = 1; i < originalLength; i++)
            {
                char c = content[i];

                if ((inString || inChar) && c == '\\' && content[i + 1] == '\\')
                {
                    content = content.Remove(i, 2);
                    content = content.Insert(i, "  ");
                }
                else if (c == '"' && content[i - 1] != '\\' && inStreamComment == false && inLineComment == false && inChar == false)
                {
                    inString = !inString;
                }
                else if (c == '\'' && content[i - 1] != '\\' && inStreamComment == false && inLineComment == false && inString == false)
                {
                    inChar = !inChar;
                }
                else if (c == '/' && content[i + 1] == '/' && inString == false && inChar == false)
                {
                    inLineComment = true;
                    i += 2;
                }
                else if (c == '/' && content[i + 1] == '*' && inLineComment == false && inString == false && inChar == false)
                {
                    inStreamComment = true;
                }
                else if (c == '*' && content[i + 1] == '/' && inString == false && inChar == false)
                {
                    inStreamComment = false;
                    if (inLineComment == false)
                    {
                        i += 2;
                    }
                }
                else if (c == '\n')
                {
                    inLineComment = false;
                    inString = false;
                    inChar = false;
                }

                if (inStreamComment == false && inLineComment == false)
                {
                    noStringContent += c;
                }
            }

            contentLen = noStringContent.Length;
            content = Environment.NewLine + noStringContent + Environment.NewLine;

            string res = "";
            int braceNest = 0;
            int maxNest = 0;
            int bracketNest = 0;

            for (int i = contentLen - 1; i >= 0; i--)
            {
                char c = content[i];

                if (c == '}')
                    braceNest++;
                else if (c == '{')
                    braceNest--;
                else if (c == ')')
                    bracketNest++;
                else if (c == '(')
                    bracketNest--;

                maxNest = Convert.ToInt32(Math.Min(maxNest, braceNest));

                if (braceNest <= maxNest)
                    res = c + res;
            }

            Regex r = new Regex("([^a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(\\s*)([^a-zA-Z0-9_])", RegexOptions.Multiline);
            Match m = r.Match("`" + res + "`");

            while (m.Success)
            {
                string text = m.Value;

                KeywordType type = KeywordType.Other;
                if (text.EndsWith("("))
                    type = KeywordType.Function;

                while (char.IsLetterOrDigit(text, 0) == false && text[0] != '_')
                    text = text.Substring(1);

                while (char.IsLetterOrDigit(text, text.Length - 1) == false && text[text.Length - 1] != '_')
                    text = text.Substring(0, text.Length - 1);

                CodeKeyword kw = new CodeKeyword(text, KeywordSource.User, type);
                CodeKeyword ppt1 = new CodeKeyword(text, KeywordSource.C, KeywordType.Preprocessor);
                CodeKeyword ppt2 = new CodeKeyword(text, KeywordSource.CPP, KeywordType.Preprocessor);

                if (preprocKeywords.Contains(ppt1.ListEntry) == false && preprocKeywords.Contains(ppt2.ListEntry) == false)
                    if (finalRes.Contains(kw.ListEntry) == false)
                        finalRes.Add(kw.ListEntry);

                m = m.NextMatch();
            }

            finalRes.Sort((x, y) => string.Compare(x, y));

            return finalRes;
        }
Example #24
0
        private void btnClone_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtPath.Text))
            {
                MessageBox.Show("The path cannot be empty");
                return;
            }

            if (Program.MakeSurePathExists(txtPath.Text))
            {
                string targetDir = txtPath.Text + Path.DirectorySeparatorChar + project.FileNameNoExt;
                if (Program.MakeSurePathExists(targetDir))
                {
                    AVRProject newProject = new AVRProject();
                    newProject = project.CopyProperties(newProject);
                    newProject.FileList.Clear();
                    newProject.FilePath = targetDir + Path.DirectorySeparatorChar + project.FileNameNoExt + ".avrproj";
                    foreach (KeyValuePair<string, ProjectFile> file in project.FileList)
                    {
                        try
                        {
                            string nfpath;
                            if (file.Value.FileRelProjPath.StartsWith(".."))
                            {
                                
                                if (radCopyAll.Checked)
                                {
                                    string extDir = targetDir + Path.DirectorySeparatorChar + "external_files";
                                    nfpath = extDir + Path.DirectorySeparatorChar + file.Value.FileName;
                                }
                                else
                                {
                                    nfpath = file.Value.FileAbsPath;
                                }
                            }
                            else
                            {
                                nfpath = targetDir + Path.DirectorySeparatorChar + file.Value.FileRelProjPath;
                            }

                            ProjectFile npf = new ProjectFile(nfpath, newProject);
                            npf.Options = file.Value.Options;
                            npf.ToCompile = file.Value.ToCompile;

                            if (file.Value.FileAbsPath != nfpath)
                            {
                                if (Program.MakeSurePathExists(npf.FileDir))
                                {
                                    try
                                    {
                                        File.Copy(file.Value.FileAbsPath, nfpath, true);
                                        newProject.FileList.Add(file.Key, npf);
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show("Error while copying '" + file.Key + "' to '" + nfpath + "' : " + ex.Message);
                                        return;
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Error while creating '" + npf.FileDir + "'");
                                    return;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error during the cloning process: " + ex.Message);
                            return;
                        }
                    }

                    try
                    {
                        if (chkCopyUnmanaged.Checked)
                        {
                            Program.CopyAll(new DirectoryInfo(project.DirPath), new DirectoryInfo(targetDir));
                        }

                        if (newProject.Save() == SaveResult.Successful)
                        {
                            if (chkOpenAfterClone.Checked)
                            {
                                try
                                {
                                    System.Diagnostics.Process.Start(newProject.DirPath);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("Could not open folder: " + ex.Message);
                                }
                            }

                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show("An error occured, the project XML (.avrproj) file did not save.");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error during the cloning process: " + ex.Message);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("The path cannot be found or created");
                    return;
                }
            }
            else
            {
                MessageBox.Show("The path cannot be found or created");
                return;
            }

            this.Close();
        }
Example #25
0
        private static List<string> GetAllLibraries(ProjectFile file, List<string> libList)
        {
            if (libList == null)
                libList = new List<string>();

            string content = "";

            if (fileContents.ContainsKey(file))
            {
                content = fileContents[file];
            }
            else
                return libList;

            Regex r = new Regex("^\\s*#include\\s+((\\\"\\S+\\\")|(<\\S+>))", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            Match m = r.Match(content);
            while (m.Success)
            {
                string lib = m.Groups[1].Value.Trim(new char[] { ' ', '\t', '\r', '\n', '"', '<', '>', });

                if (libList.Contains(lib) == false && lib != file.FileName)
                {
                    libList.Add(lib);

                    ProjectFile nextfile;
                    if (project.FileList.TryGetValue(lib.ToLowerInvariant(), out nextfile))
                    {
                        if (fileContents.ContainsKey(nextfile))
                        {
                            if (fileLibs.ContainsKey(nextfile) == false)
                            {
                                fileLibs.Add(nextfile, new List<string>());
                                GetAllLibraries(nextfile, fileLibs[nextfile]);
                            }

                            string[] tmpList = fileLibs[nextfile].ToArray();
                            foreach (string s in tmpList)
                            {
                                if (libList.Contains(s) == false && s != file.FileName)
                                    libList.Add(s);
                            }
                        }
                    }
                }

                m = m.NextMatch();
            }

            return libList;
        }
        private void GetCompilableFiles(string folder, List<ProjectFile> fileList, bool isLibrary)
        {
            Program.MakeSurePathExists(SettingsManagement.AppDataPath + "temp");

            // look for files which can be compiled
            if (Directory.Exists(folder))
            {
                DirectoryInfo dnfo = new DirectoryInfo(folder);
                foreach (FileInfo fnfo in dnfo.GetFiles())
                {
                    string ext = fnfo.FullName.ToLowerInvariant();
                    if (ext.EndsWith(".c") || ext.EndsWith(".cpp") || ext.EndsWith(".s") || ext.EndsWith(".h") || ext.EndsWith(".hpp"))
                    {
                        string newLoc = SettingsManagement.AppDataPath + "temp" + Path.DirectorySeparatorChar + fnfo.Name;

                        if (fnfo.Name != "main.cpp")
                        {
                            try
                            {
                                File.Copy(fnfo.FullName, newLoc, true);
                            }
                            catch (Exception ex)
                            {
                                TextBoxModify(outputTextbox, "####Error while copying " + fnfo.Name + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
                            }

                            if (ext.EndsWith(".h") == false && ext.EndsWith(".hpp") == false)
                            {

                                ProjectFile newFile = new ProjectFile(newLoc, workingProject);
                                fileList.Add(newFile);

                            }
                        }
                    }
                }

                // recursively find files within subdirectories
                foreach (DirectoryInfo nextDir in dnfo.GetDirectories())
                {
                    if (isLibrary)
                    {
                        if (nextDir.Name.ToLowerInvariant() == "utility")
                            GetCompilableFiles(nextDir.FullName, fileList, true);
                        else
                        {
                            try
                            {
                                if (nextDir.Name != "examples")
                                    Program.CopyAll(nextDir, new DirectoryInfo(SettingsManagement.AppDataPath + "temp" + Path.DirectorySeparatorChar + nextDir.Name));
                            }
                            catch (Exception ex)
                            {
                                TextBoxModify(outputTextbox, "####Error while copying " + nextDir.Name + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
                            }
                        }
                    }
                    else
                        GetCompilableFiles(nextDir.FullName, fileList, false);
                }
            }
        }
Example #27
0
        private static void GetAllKeywords(ProjectFile file)
        {
            if (fileKeywords.ContainsKey(file) == false)
                fileKeywords.Add(file, new Dictionary<string, CodeKeyword>());

            foreach (CodeKeyword kw in CKeywords.Values)
            {
                if (fileKeywords[file].ContainsKey(kw.Text) == false)
                    fileKeywords[file].Add(kw.Text, kw);
            }

            if (file.FileExt == "cpp" || file.FileExt == "pde")
            {
                foreach (CodeKeyword kw in CPPKeywords.Values)
                {
                    if (fileKeywords[file].ContainsKey(kw.Text) == false)
                        fileKeywords[file].Add(kw.Text, kw);
                }
            }

            if (file.FileExt == "pde")
            {
                foreach (CodeKeyword kw in ArduinoKeywords.Values)
                {
                    if (fileKeywords[file].ContainsKey(kw.Text) == false)
                        fileKeywords[file].Add(kw.Text, kw);
                }
            }

            List<string> libList = null;
            if (fileLibs.ContainsKey(file))
            {
                libList = fileLibs[file];
            }
            else
            {
                GetAllLibraries(file, libList);
            }

            foreach (string libName in libList)
            {
                if (AVRLibcKeywords.ContainsKey(libName))
                {
                    foreach (CodeKeyword kw in AVRLibcKeywords[libName].Values)
                    {
                        if (fileKeywords[file].ContainsKey(kw.Text) == false)
                            fileKeywords[file].Add(kw.Text, kw);
                    }
                }
                else if (project.FileList.ContainsKey(libName.ToLowerInvariant()))
                {
                    if (fileKeywords.ContainsKey(project.FileList[libName.ToLowerInvariant()]) == false)
                    {
                        GetAllKeywords(project.FileList[libName.ToLowerInvariant()]);
                    }

                    foreach (CodeKeyword kw in fileKeywords[project.FileList[libName.ToLowerInvariant()]].Values)
                    {
                        if (fileKeywords[file].ContainsKey(kw.Text) == false)
                            fileKeywords[file].Add(kw.Text, kw);
                    }
                }
            }

            //return;

            string content = "";

            if (fileContents.ContainsKey(file))
            {
                content = fileContents[file];
            }
            else
                return;

            int contentLen = content.Length;
            content = Environment.NewLine + content + Environment.NewLine;

            bool inString = false;
            bool inChar = false;

            int nest = 0;

            string res = "";

            for (int i = 2; i < contentLen + 2; i++)
            {
                if ((inString || inChar) && content[i] == '\\' && content[i + 1] == '\\')
                {
                    content = content.Remove(i, 2);
                    content = content.Insert(i, "  ");
                }
                else if (content[i] == '"' && content[i - 1] != '\\' && inChar == false)
                    inString = !inString;
                else if (content[i] == '\'' && content[i - 1] != '\\' && inString == false)
                    inChar = !inChar;
                else if ((content[i] == '(' || content[i] == '{') && inString == false && inChar == false)
                    nest++;
                else if ((content[i] == ')' || content[i] == '}') && inString == false && inChar == false)
                    nest--;

                if (inChar == false && inString == false && nest == 0)
                    res += content[i];
            }

            Regex r = new Regex("([^a-zA-Z0-9_])([a-zA-Z_][a-zA-Z0-9_]*)(\\s*)([^a-zA-Z0-9_])", RegexOptions.Multiline);
            Match m = r.Match("`" + res + "`");

            while (m.Success)
            {
                string text = m.Value;

                KeywordType type = KeywordType.Other;
                if (text.EndsWith("("))
                    type = KeywordType.Function;

                while (char.IsLetterOrDigit(text, 0) == false && text[0] != '_')
                    text = text.Substring(1);

                while (char.IsLetterOrDigit(text, text.Length - 1) == false && text[text.Length - 1] != '_')
                    text = text.Substring(0, text.Length - 1);

                if (fileKeywords[file].ContainsKey(text) == false)
                    fileKeywords[file].Add(text, new CodeKeyword(text, KeywordSource.User, type));

                m = m.NextMatch();
            }
        }
 private string GetFileContents(ProjectFile file)
 {
     string res = "";
     try
     {
         StreamReader reader = new StreamReader(file.FileAbsPath);
         res = reader.ReadToEnd();
         reader.Close();
     }
     catch (Exception ex)
     {
         TextBoxModify(outputTextbox, "####Error while retrieving file contents of " + file.FileName + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
     }
     return res;
 }
Example #29
0
        public EditorPanel(ProjectFile file, AVRProject project, IDEWindow parent)
        {
            InitializeComponent();

            this.parent = parent;
            this.file = file;
            this.project = project;

            SettingsManagement.LoadEditorState(this);

            this.Icon = GraphicsResx.file;
        }
        public bool Compile(ProjectFile file)
        {
            string outputAbsPath = workingProject.DirPath + Path.DirectorySeparatorChar + workingProject.OutputDir;

            // create the directory
            if (Program.MakeSurePathExists(outputAbsPath) == false)
                return false;

            string objectFileAbsPath = outputAbsPath + Path.DirectorySeparatorChar + file.FileNameNoExt + ".o";

            // delete object file if existing
            if (File.Exists(objectFileAbsPath))
            {
                try
                {
                    File.Delete(objectFileAbsPath);
                }
                catch (Exception ex)
                {
                    TextBoxModify(outputTextbox, "####Error: object file could not be deleted at " + objectFileAbsPath + ", " + ex.Message, TextBoxChangeMode.PrependNewLine);
                }
            }

            // construct options and arguments for avr-gcc

            string args = "";
            foreach (string path in workingProject.IncludeDirList)
            {
                if(string.IsNullOrEmpty(path) == false)
                    args += "-I\"" + path + "\" ";
            }
            args += "-I\"" + file.FileDir + "\" ";

            string checklist = "";
            
            if (project.PackStructs)
                checklist += "-fpack-struct ";

            if (project.ShortEnums)
                checklist += "-fshort-enums ";

            if (project.UnsignedChars)
                checklist += "-funsigned-char ";

            if (project.UnsignedBitfields)
                checklist += "-funsigned-bitfields ";

            if (project.FunctionSections)
                checklist += "-ffunction-sections ";

            if (project.DataSections)
                checklist += "-fdata-sections ";

            string asmflags = "";

            if (file.FileExt == "s")
                asmflags += "-x assembler-with-cpp -Wa,-gdwarf2";

            string fileTypeOptions = "";
            if (file.FileExt == "c")
                fileTypeOptions = workingProject.OtherOptionsForC;
            else if (file.FileExt == "cpp" || file.FileExt == "cxx")
                fileTypeOptions = workingProject.OtherOptionsForCPP;
            else if (file.FileExt == "s")
                fileTypeOptions = workingProject.OtherOptionsForS;

            string clkStr = " ";
            if (project.ClockFreq != 0)
                clkStr = String.Format(" -DF_CPU={0:0}UL ", Math.Round(project.ClockFreq));

            args += String.Format(" -mmcu={0}{1}{2} {3} {4} -MD -MP -MT {5}.o {6} -c {7} {8} \"{9}\"",
                workingProject.Device.ToLowerInvariant(),
                clkStr,
                workingProject.Optimization,
                checklist,
                workingProject.OtherOptions,
                file.FileNameNoExt,
                asmflags,
                file.Options,
                fileTypeOptions,
                file.FileAbsPath.Replace('\\', '/')
            );

            ProcessStartInfo psi = null;

            // c++ uses avr-g++ while c uses avr-gcc, duh
            if (file.FileExt == "cpp" || file.FileExt == "cxx")
            {
                TextBoxModify(outputTextbox, "Execute: avr-g++ " + args, TextBoxChangeMode.PrependNewLine);
                psi = new ProcessStartInfo("avr-g++", args);
            }
            else
            {
                TextBoxModify(outputTextbox, "Execute: avr-gcc " + args, TextBoxChangeMode.PrependNewLine);
                psi = new ProcessStartInfo("avr-gcc", args);
            }

            ProjectBuilder.SetEnviroVarsForProc(psi);
            psi.WorkingDirectory = outputAbsPath + Path.DirectorySeparatorChar;
            psi.UseShellExecute = false;
            psi.RedirectStandardError = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.CreateNoWindow = true;
            Process avrgcc = new Process();
            avrgcc.StartInfo = psi;
            try
            {
                if (avrgcc.Start())
                {
                    StreamReader stderr = avrgcc.StandardError;
                    ReadErrAndWarnings(stderr, false);
                    StreamReader stdout = avrgcc.StandardOutput;
                    ReadErrAndWarnings(stdout, false);
                    avrgcc.WaitForExit(10000);
                }
                else
                {
                    TextBoxModify(outputTextbox, "####Error: unable to start avr-gcc", TextBoxChangeMode.PrependNewLine);
                    return false;
                }
            }
            catch (Exception ex)
            {
                TextBoxModify(outputTextbox, "####Error: unable to start avr-gcc, " + ex.Message, TextBoxChangeMode.PrependNewLine);
                return false;
            }

            if (File.Exists(objectFileAbsPath))
            {
                return true;
            }
            else
            {
                TextBoxModify(outputTextbox, "####Error: object file not created at " + objectFileAbsPath, TextBoxChangeMode.PrependNewLine);
                return false;
            }
        }
        public FileEditorTab(ProjectFile myFile, TreeNode treeNode)
        {
            this.myFile = myFile;
            this.myNode = treeNode;

            myTabPage = new TabPage(this.myFile.FileName);

            myScint      = new Scintilla();
            myScint.Dock = DockStyle.Fill;
            myScint.ConfigurationManager.Language = "cs";
            myScint.Lexing.SetKeywords(0, "if else for do while	switch case default goto break continue return sizeof free malloc calloc PSTR ISR SIGNAL");
            myScint.Lexing.SetKeywords(1, "void inline extern signed unsigned typedef union struct enum volatile static const byte char short int long word dword float double bool bit bitfield byte uchar ushort uint ulong uword uint8_t uint16_t uint32_t uint64_t int8_t int16_t int32_t int64_t");

            for (int i = 0; i < 256; i++)
            {
                try
                {
                    if (myScint.Styles[i].ForeColor == Color.Teal)
                    {
                        myScint.Styles[i].ForeColor = Color.Purple;
                    }
                    if (myScint.Styles[i].ForeColor == Color.Orange)
                    {
                        myScint.Styles[i].ForeColor = Color.DarkBlue;
                    }
                    if (myScint.Styles[i].ForeColor == Color.DarkGoldenrod)
                    {
                        myScint.Styles[i].ForeColor = Color.BlueViolet;
                    }
                }
                catch
                {
                    break;
                }
            }

            myScint.Folding.IsEnabled    = true;
            myScint.Folding.MarkerScheme = FoldMarkerScheme.BoxPlusMinus;

            myScint.Margins[0].Width = 20;
            myScint.Margins[1].Width = 10;
            myScint.Margins[2].Width = 10;

            myScint.IsBraceMatching = true;
            myScint.MatchBraces     = true;

            myScint.Scrolling.ScrollBars = ScrollBars.Vertical;

            myScint.LineWrap.Mode = WrapMode.Word;

            myScint.Indentation.SmartIndentType = SmartIndent.CPP;
            myScint.Indentation.TabIndents      = true;
            myScint.Indentation.UseTabs         = true;
            myScint.Indentation.IndentWidth     = 4;
            myScint.Indentation.ShowGuides      = true;

            myScint.Modified     = false;
            myScint.TextChanged += new EventHandler(MakeChange);

            Load();

            myTabPage.Controls.Add(myScint);

            externChangeWatcher.Filter = myFile.FileName;
            externChangeWatcher.Path   = myFile.FileDir + "\\";
            externChangeWatcher.IncludeSubdirectories = false;
            externChangeWatcher.NotifyFilter          = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.DirectoryName;

            externChangeWatcher.Renamed += new RenamedEventHandler(externChangeWatcher_Renamed);
            externChangeWatcher.Deleted += new FileSystemEventHandler(externChangeWatcher_Deleted);
            externChangeWatcher.Changed += new FileSystemEventHandler(externChangeWatcher_Changed);
        }
 private void btnNewFile_Click(object sender, EventArgs e)
 {
     SaveFileDialog sfd = new SaveFileDialog();
     sfd.OverwritePrompt = false;
     sfd.Filter = "C Code (*.c)|*.c|Header File (*.h)|*.h|Assembly Code (*.S)|*.S";
     if (sfd.ShowDialog() == DialogResult.OK)
     {
         string fname = sfd.FileName.Substring(sfd.FileName.IndexOf('\\') + 1);
         if (fname.Contains(' ') == false)
         {
             ProjectFile pf = new ProjectFile(sfd.FileName, myProject.DirPath);
             if (myProject.FileList.TryGetValue(pf.FileName, out pf) == false)
             {
                 pf = new ProjectFile(sfd.FileName, myProject.DirPath);
                 myProject.FileList.Add(pf.FileName, pf);
                 ((frmProjIDE)(this.ParentForm)).RefreshFileTree();
             }
             else
             {
                 MessageBox.Show("Please No Duplicate File Names, " + fname + " is already used.");
             }
         }
         else
         {
             MessageBox.Show("Please No Spaces in File Name");
         }
     }
 }
Example #33
0
        private void btnCreate_Click(object sender, EventArgs e)
        {
            string f = txtFileName.Text.Trim();

            if (string.IsNullOrEmpty(f))
            {
                MessageBox.Show("File name must not be blank");
                return;
            }
            
            string fileName;
            if (f.EndsWith("."))
                fileName = f + this.SelectedExtension.TrimStart('.');
            else if (f.Contains("."))
                fileName = f;
            else
                fileName = f + "." + this.SelectedExtension.TrimStart('.');

            if (
                fileName.Contains(" ") ||
                fileName.Contains("\t") ||
                fileName.Contains("\r") ||
                fileName.Contains("\n") ||
                fileName.Contains("\0") ||
                fileName.Contains("\\") ||
                fileName.Contains("/")
                )
            {
                MessageBox.Show("Invalid Character in File Name");
                return;
            }

            foreach (char c in Path.GetInvalidFileNameChars())
            {
                if (fileName.Contains(char.ToString(c)))
                {
                    MessageBox.Show("Invalid Character '" + c + "' in File Name");
                    return;
                }
            }

            string fileAbsPath = txtDirLoc.Text + fileName;
            foreach (char c in Path.GetInvalidPathChars())
            {
                if (fileAbsPath.Contains(char.ToString(c)))
                {
                    MessageBox.Show("Invalid Character '" + c + "' in File Path");
                    return;
                }
            }

            string fileNameL = fileName.ToLowerInvariant();

            if (project.FileList.ContainsKey(fileNameL))
            {
                if (project.FileList[fileNameL].Exists)
                {
                    MessageBox.Show("File already exists in the project");
                    return;
                }
            }
            else
            {
                project.FileList.Add(fileNameL, new ProjectFile(fileAbsPath, project));
            }

            if (project.FileList[fileNameL].Exists == false)
            {
                if (((string)dropTemplates.Items[dropTemplates.SelectedIndex]) != "none")
                {
                    try
                    {
                        File.WriteAllText(fileAbsPath, FileTemplate.CreateFile(fileName, project.FileNameNoExt, ((string)dropTemplates.Items[dropTemplates.SelectedIndex]) + ".txt"));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error writing file from template, " + ex.Message);
                    }
                }
                else
                {
                    try
                    {
                        File.WriteAllText(fileAbsPath, "");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error creating file, " + ex.Message);
                    }
                }
            }

            createdFile = project.FileList[fileNameL];

            if (project.FileList.Count == 1)
                project.FileList[fileNameL].IsOpen = true;

            if (project.Save() == SaveResult.Failed)
            {
                MessageBox.Show("Error saving project");
            }

            SettingsManagement.LastFileExt = createdFile.FileExt;

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Example #34
0
        private void btnCreate_Click(object sender, EventArgs e)
        {
            string iniFilename = txtInitialFilename.Text.Trim();
            bool hasIniFile = !string.IsNullOrEmpty(iniFilename);
            hasIniFile = false;
            string projFilename = txtProjName.Text.Trim();

            if (string.IsNullOrEmpty(projFilename))
            {
                MessageBox.Show("The project name can't be blank");
                return;
            }

            char[] forbidChars = Path.GetInvalidFileNameChars();
            foreach (char c in forbidChars)
            {
                if (hasIniFile && iniFilename.Contains(c))
                {
                    MessageBox.Show("Illegal Character in Initial File Name");
                    return;
                }

                if (projFilename.Contains(c))
                {
                    MessageBox.Show("Illegal Character in Project File Name");
                    return;
                }
            }

            if (hasIniFile)
            {
                if (iniFilename.Contains('/') || iniFilename.Contains('\\') || iniFilename.Contains(Path.DirectorySeparatorChar) || iniFilename.Contains(Path.AltDirectorySeparatorChar))
                {
                    MessageBox.Show("Illegal Character in Initial File Name");
                    return;
                }

                if (iniFilename.Contains('.') || iniFilename.Contains(' ') || iniFilename.Contains('\t'))
                {
                    MessageBox.Show("No Spaces or Dots are Allowed in Initial File Name");
                    return;
                }
            }

            if (projFilename.Contains('/') || projFilename.Contains('\\') || projFilename.Contains(Path.DirectorySeparatorChar) || projFilename.Contains(Path.AltDirectorySeparatorChar))
            {
                MessageBox.Show("Illegal Character in Project File Name");
                return;
            }

            if (projFilename.Contains('.'))
            {
                MessageBox.Show("No Dots are Allowed in Project File Name");
                return;
            }

            string folderPath = Program.CleanFilePath(txtFolderPath.Text);

            if (Program.MakeSurePathExists(folderPath) == false)
            //if (Directory.Exists(folderPath))
            {
                MessageBox.Show("Error Creating Folder");
                //MessageBox.Show("Error: Folder Invalid");
                return;
            }

            string projFilePath = folderPath + Path.DirectorySeparatorChar + projFilename + ".avrproj";

            project.FilePath = projFilePath;

            string ext = "c";
            if (((string)dropFileType.Items[dropFileType.SelectedIndex]).Contains("C++"))
                ext = "cpp";
            else if (((string)dropFileType.Items[dropFileType.SelectedIndex]).Contains("C"))
                ext = "c";
            else if (((string)dropFileType.Items[dropFileType.SelectedIndex]).Contains("Arduino"))
                ext = "pde";

            string iniFilePath = folderPath + Path.DirectorySeparatorChar + iniFilename + "." + ext;

            if (File.Exists(projFilePath))
            {
                if (MessageBox.Show("Project File Already Exists at the Location, Overwrite it?", "Overwrite?", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
            }

            bool merge = false;

            if (hasIniFile && File.Exists(iniFilePath))
            {
                if (MessageBox.Show("Initial File Already Exists at the Location, Merge it with your project?", "Merge File?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    merge = true;
                }
                else if (MessageBox.Show("Maybe you'd rather overwrite it with a blank file?", "Overwrite File?", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
            }

            if (hasIniFile)
            {
                if (merge == false)
                {
                    try
                    {
                        StreamWriter writer = new StreamWriter(iniFilePath);
                        if (ext == "pde")
                        {
                            writer.Write(FileTemplate.CreateFile(iniFilename + "." + ext, projFilename, "initialpde.txt"));
                        }
                        else
                        {
                            writer.Write(FileTemplate.CreateFile(iniFilename + "." + ext, projFilename, "initialmain.txt"));
                        }
                        writer.WriteLine();
                        writer.Close();
                    }
                    catch (Exception ex)
                    {
                        ErrorReportWindow.Show(ex, "Error while creating initial file");
                        
                    }
                }

                ProjectFile newFile = new ProjectFile(iniFilePath, project);
                newFile.IsOpen = true;
                project.FileList.Add(newFile.FileName.ToLowerInvariant(), newFile);
            }

            ProjTemplate.ApplyTemplate((string)dropTemplates.Items[dropTemplates.SelectedIndex], project);

            project.FilePath = projFilePath;

            FileAddWizard faw = new FileAddWizard(project);
            faw.ShowDialog();

            if (project.Save(projFilePath) == false)
            {
                MessageBox.Show("Error While Saving Project");
            }
            else
            {
                if (project.Open(projFilePath) == false)
                {
                    MessageBox.Show("Error While Opening Project");
                }
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Example #35
0
        static public bool ApplyTemplate(string name, AVRProject proj)
        {
            int appCnt = 0;

            XmlElement template;

            if (templates.TryGetValue(name, out template))
            {
                XmlElement docx = (XmlElement)template.CloneNode(true);

                List <string> alreadyInherited = new List <string>();
                alreadyInherited.Add(name);
                bool foundNew;
                do
                {
                    foundNew = false;
                    string inheritedInnerXml = "";
                    foreach (XmlElement param in docx.GetElementsByTagName("Inherit"))
                    {
                        string inheritName = param.InnerText.Trim();
                        if (alreadyInherited.Contains(inheritName) == false)
                        {
                            XmlElement inherited;
                            if (templates.TryGetValue(inheritName, out inherited))
                            {
                                inheritedInnerXml += inherited.InnerXml;
                                alreadyInherited.Add(inheritName);
                                foundNew = true;
                            }
                        }
                    }
                    docx.InnerXml += inheritedInnerXml;
                } while (foundNew);

                AVRProject.LoadTemplateCommonProperties(ref appCnt, docx, proj);

                if (appCnt >= 2)
                {
                    proj.HasBeenConfigged = true;
                }

                try
                {
                    foreach (XmlElement i in docx.GetElementsByTagName("CreateFile"))
                    {
                        string fname = i.GetAttribute("name");
                        if (string.IsNullOrEmpty(fname) == false)
                        {
                            try
                            {
                                ProjectFile f = new ProjectFile(Program.AbsPathFromRel(proj.DirPath, fname), proj);
                                if (proj.FileList.ContainsKey(fname.ToLowerInvariant()) == false)
                                {
                                    proj.FileList.Add(fname.ToLowerInvariant(), f);
                                    proj.ShouldReloadFiles = true;

                                    if (f.Exists == false)
                                    {
                                        Program.MakeSurePathExists(f.FileDir);
                                        File.WriteAllText(f.FileAbsPath, " ");

                                        foreach (XmlElement k in i.GetElementsByTagName("Template"))
                                        {
                                            File.WriteAllText(f.FileAbsPath, FileTemplate.CreateFile(f.FileName, proj.FileNameNoExt, k.InnerText));
                                            break;
                                        }
                                    }
                                }
                            }
                            catch { }
                        }
                    }
                }
                catch
                {
                    return(false);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }