<|start_filename|>AmpyFileManager/Manager.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ScintillaNET;

namespace AmpyFileManager
{
    public partial class Manager : Form
    {
        private const string NEW_FILENAME = "<new>";
        private const string LF = "\n";
        private const string CR = "\r";
        private const string CRLF = "\r\n";
        private const string LBracket = "[";
        private const string RBracket = "]";

        private bool _FileDirty = false;
        private string _BackupPath = string.Empty;
        private string _SessionPath = string.Empty;
        private string _CurrentPath = string.Empty;
        private string _CurrentFile = string.Empty;
        private string _EditableExtensions = string.Empty;
        private string _command = string.Empty;
        private string _readBuffer = string.Empty;
        private bool _JustOpened = false;
        private string _runCommand = string.Empty;
        private int _bufferLimit = 16384;
        private int _bufferResetSize = 2048;

        private bool _externalTerminal = true;
        private string _terminalApp = "putty";
        private string _terminalAppArgs = "-load \"repl\" -serial {PORT}";

        private ESPRoutines _ESP;   // Wrapper for AMPY invocations

        public Manager(ESPRoutines ESP)
        {
            _ESP = ESP;
            InitializeComponent();            
        }

        #region Events

        private void Manager_Load(object sender, EventArgs e)
        {
            this.Text = "Ampy File Manager (" + _ESP.COMM_PORT + ")";

            _externalTerminal = (ConfigurationManager.AppSettings["REPL"] == "E");
            if (_externalTerminal)
            {
                _terminalApp = ConfigurationManager.AppSettings["TerminalApp"];
                _terminalAppArgs = ConfigurationManager.AppSettings["TerminalAppArgs"];
                splitContainer2.Panel2.Visible = false;
                splitContainer2.SplitterDistance = splitContainer2.Height;
            }

            // Get the dir where we save things
            string saveDir = ConfigurationManager.AppSettings["SaveDir"];
            if (String.IsNullOrWhiteSpace(saveDir))
                saveDir = Path.GetDirectoryName(Application.ExecutablePath);

            btnRun.Visible = (ConfigurationManager.AppSettings["ShowRunButton"] == "Y");
            btnBackup.Visible = (ConfigurationManager.AppSettings["ShowBackupButton"] == "Y");

            // directory for all backup files
            _BackupPath = Path.Combine(saveDir, "backups");
            if (!Directory.Exists(_BackupPath))
                Directory.CreateDirectory(_BackupPath);

            // Where we store our files while they are being edited
            string uniqueSessions = ConfigurationManager.AppSettings["UniqueSessions"];
            string SessionRoot = Path.Combine(saveDir, "session");
            if (uniqueSessions.Trim().ToUpper().StartsWith("Y"))
                _SessionPath = Path.Combine(SessionRoot, DateTime.Now.ToString("SyyyyMMdd-HHmm"));
            else
                _SessionPath = SessionRoot;
            if (!Directory.Exists(_SessionPath))
                Directory.CreateDirectory(_SessionPath);

            // load help links
            LoadHelpDropdown();

            // Setup tooltips
            toolTip1.SetToolTip(btnBackup, "Make a local backup of all the files on the device");
            toolTip1.SetToolTip(btnChangeMode, "Go to the MicroPython REPL");
            toolTip1.SetToolTip(btnDelete, "Delete the selected file or directory permanently from the device");
            toolTip1.SetToolTip(btnExport, "Export the selected file from the device to your computer");
            toolTip1.SetToolTip(btnLoad, "Import an external file to the device");
            toolTip1.SetToolTip(btnMkdir, "Make a sub-directory under the current directory");
            toolTip1.SetToolTip(btnMove, "Move (rename) the selected file");
            toolTip1.SetToolTip(btnNew, "Create a new file");
            toolTip1.SetToolTip(btnOpen, "Open the selected file for editing or directory for viewing");
            toolTip1.SetToolTip(btnRefresh, "Re-read the file list for the current directory");
            toolTip1.SetToolTip(btnRun, "Run the currently selected file");
            toolTip1.SetToolTip(btnSave, "Save the current file");
            toolTip1.SetToolTip(btnSaveAs, "Save the current file to the current directory with the specified name");
            toolTip1.SetToolTip(btnReplaceAll, "Simple search-and-replace for current file");
            toolTip1.SetToolTip(cboHelp, "Help Links");

            // these are the file that can be opened and edited
            _EditableExtensions = ConfigurationManager.AppSettings["EditExtensions"];
            if (String.IsNullOrWhiteSpace(_EditableExtensions))
                _EditableExtensions = "py,txt,html,js,css,json";

            // set some colors
            string bcolor = ConfigurationManager.AppSettings["ExplorerColor"];
            if (bcolor.Contains(","))
            {
                string[] rgb = bcolor.Split(',');
                lstDirectory.BackColor = Color.FromArgb(Convert.ToInt32(rgb[0]), Convert.ToInt32(rgb[1]), Convert.ToInt32(rgb[2]));
            }
            else
                lstDirectory.BackColor = Color.FromName(bcolor);

            txtTerminal.Font = new Font(ConfigurationManager.AppSettings["TerminalFont"], Convert.ToSingle(ConfigurationManager.AppSettings["TerminalFontSize"]), FontStyle.Regular);
            lstDirectory.Font = new Font(ConfigurationManager.AppSettings["DirectoryFont"], Convert.ToSingle(ConfigurationManager.AppSettings["DirectoryFontSize"]), FontStyle.Regular);

            ConfigureForPython(scintilla1);

            RefreshFileList();

            ResetNew();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (OKToContinue())
                OpenItem();
        }

        private void lstDirectory_DoubleClick(object sender, EventArgs e)
        {
            if (OKToContinue())
                OpenItem();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            ButtonSave();
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            if (_CurrentFile == NEW_FILENAME)
                ButtonSave();
            else
            {
                string oldFilename = _CurrentFile;
                _CurrentFile = NEW_FILENAME;
                bool saved = DoSave(oldFilename);
                if (saved)
                {
                    lblCurrentFile.Text = GetFileOnly(_CurrentFile);
                    _FileDirty = false;
                    RefreshFileList();
                }
                else
                    _CurrentFile = oldFilename;
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (OKToContinue())
                ResetNew();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            string selectedItem = lstDirectory.Text;
            if (selectedItem != "")
            {
                if (selectedItem.StartsWith(LBracket))
                {
                    string DirToDelete = selectedItem.Replace(LBracket, "").Replace(RBracket, "");
                    if (DirToDelete != "..")
                    {
                        string FullDirToDelete = (_CurrentPath == "") ? DirToDelete : _CurrentPath + "/" + DirToDelete;
                        if (MessageBox.Show("Are you sure you want to delete the directory '" + FullDirToDelete + "' and all of it's contents?", "Confirm Delete", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
                        {
                            Cursor.Current = Cursors.WaitCursor;
                            _ESP.DeleteDir(FullDirToDelete);
                            Cursor.Current = Cursors.Default;
                            RefreshFileList();
                        }
                    }
                }
                else 
                {
                    string FileToDelete = (_CurrentPath == "") ? selectedItem : _CurrentPath + "/" + selectedItem;
                    if (MessageBox.Show("Are you sure you want to delete '" + FileToDelete + "'?", "Confirm Delete", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        _ESP.DeleteFile(FileToDelete);
                        Cursor.Current = Cursors.Default;
                        RefreshFileList();
                    }
                }
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string newFile = openFileDialog1.FileName;
                string newFilename = Path.GetFileName(newFile);
                string FileToAdd = (_CurrentPath == "") ? newFilename : _CurrentPath + "/" + newFilename;
                Cursor.Current = Cursors.WaitCursor;
                _ESP.PutFile(newFile, FileToAdd);
                Cursor.Current = Cursors.Default;
                RefreshFileList();
            }
        }

        private void btnMove_Click(object sender, EventArgs e)
        {
            string FileToMove = "";
            string selectedItem = lstDirectory.Text;
            if (selectedItem != "")
            {
                if (!selectedItem.StartsWith(LBracket))
                {
                    FileToMove = (_CurrentPath == "") ? selectedItem : _CurrentPath + "/" + selectedItem;
                }
                else
                    MessageBox.Show("Can only move files.", "Not Supported");
            }

            if (FileToMove != "")
            {
                string filename = Microsoft.VisualBasic.Interaction.InputBox("New Path and Filename:", "Move File", "");
                if (filename != "")
                {
                    if (filename.IndexOf(".") > 0)
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        _ESP.MoveFile(FileToMove, filename);
                        Cursor.Current = Cursors.Default;
                        RefreshFileList();
                    }
                    else
                        MessageBox.Show("Filename must have an extension.");
                }
            }
        }

        private void btnMkdir_Click(object sender, EventArgs e)
        {
            string newdir = Microsoft.VisualBasic.Interaction.InputBox("New directory under " + lblCurrentDirectory.Text + ":", "Create Directory", "");
            if (newdir != "")
            {
                if (!newdir.Contains("."))
                {
                    string newdirfull = (_CurrentPath == "") ? newdir : _CurrentPath + "/" + newdir;
                    Cursor.Current = Cursors.WaitCursor;
                    _ESP.CreateDir(newdirfull);
                    Cursor.Current = Cursors.Default;
                    RefreshFileList();
                }
                else
                    MessageBox.Show("Cannot create new directory with a period in the name.");
            }
        }

        private void btnBackup_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Backup all files?", "Confirm", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Backup();
                MessageBox.Show("Backup complete.");
            }
        }

        private void scintilla1_TextChanged(object sender, EventArgs e)
        {
            _FileDirty = true;
        }

        private void Manager_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !OKToContinue();
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    _readBuffer = serialPort1.ReadExisting();
                    this.Invoke(new EventHandler(DoUpdate));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "serialPort1_DataReceived() Error");
            }
        }

        private void btnControlC_Click(object sender, EventArgs e)
        {
            InvokeControlC();
            txtTerminal.Focus();
        }

        private void btnControlD_Click(object sender, EventArgs e)
        {
            InvokeControlD();
            txtTerminal.Focus();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshFileList();
        }

        private void tmrCommStatus_Tick(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen && picCommStatus.BackColor != Color.Green)
            {
                picCommStatus.BackColor = Color.Green;
            }
            else if (!serialPort1.IsOpen && picCommStatus.BackColor != Color.Red)
            { 
                picCommStatus.BackColor = Color.Red;
            }

            if (_FileDirty && lblCurrentFile.ForeColor != Color.Red)
                lblCurrentFile.ForeColor = Color.Red;
            else if (!_FileDirty && lblCurrentFile.ForeColor == Color.Red)
                lblCurrentFile.ForeColor = Color.Black;            
        }

        private void btnChangeMode_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
                RefreshFileList();
            else
            {
                if (!_externalTerminal)
                {
                    OpenComm();
                    txtTerminal.Focus();
                }
                else
                {
                    Process p = new Process();
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    p.StartInfo.FileName = _terminalApp;
                    p.StartInfo.Arguments = _terminalAppArgs.Replace("{PORT}", _ESP.COMM_PORT).Replace("{PORTNUM}", Convert.ToInt16(_ESP.COMM_PORT.Replace("COM", "")).ToString());
                    p.Start();
                    //string title = GetCaptionOfActiveWindow();
                    //while (title.Contains("Ampy"))
                    //{
                    //    Application.DoEvents();
                    //    title = GetCaptionOfActiveWindow();
                    //}
                    //SendKeys.SendWait("{ENTER}");
                    p.WaitForExit();
                }
            }
        }

        private void btnLoadHelp_Click(object sender, EventArgs e)
        {
            LoadHelp();
        }

        private void txtTerminal_Enter(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
                OpenComm();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            string selectedItem = lstDirectory.Text;
            if (selectedItem != "")
            {
                if (selectedItem.Substring(0, 1) != LBracket)
                {
                    if (selectedItem.ToLower().EndsWith(".py"))
                    {
                        _runCommand = "import " + selectedItem.Substring(0, selectedItem.Length - 3);
                        if (_externalTerminal)
                        {
                            Process p = new Process();
                            p.StartInfo.UseShellExecute = false;
                            p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                            p.StartInfo.FileName = _terminalApp;
                            p.StartInfo.Arguments = _terminalAppArgs.Replace("{PORT}", _ESP.COMM_PORT);
                            p.Start();
                            string title = GetCaptionOfActiveWindow();
                            while (title.Contains("Ampy"))
                            {
                                Application.DoEvents();
                                title = GetCaptionOfActiveWindow();
                            }
                            SendKeys.SendWait("{ENTER}" + _runCommand + "{ENTER}");
                            p.WaitForExit();
                        }
                        else
                        {
                            OpenComm();
                            txtTerminal.Focus();
                            tmrRunCommand.Enabled = true;
                        }
                    }
                }
            }
        }

        private void txtTerminal_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    char[] key = new char[1];
                    key[0] = e.KeyChar;
                    serialPort1.Write(key, 0, 1);
                    e.Handled = true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void tmrRunCommand_Tick(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen && _runCommand != "")
            {
                serialPort1.WriteLine(_runCommand);
                _runCommand = "";
                tmrRunCommand.Enabled = false;
            }
        }

        private void txtTerminal_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
                e.IsInputKey = true;
        }

        private void txtTerminal_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                byte[] b = { 27, 91, 65 };
                serialPort1.Write(b, 0, 3);
            }
            else if (e.KeyCode == Keys.Down)
            {
                byte[] b = { 27, 91, 66 };
                serialPort1.Write(b, 0, 3);
            }
            else if ((e.KeyCode == Keys.V && e.Control) || (e.KeyCode == Keys.Insert && e.Shift))
            {
                serialPort1.Write(Clipboard.GetText());
            }
        }

        private void btnCustom_Click(object sender, EventArgs e)
        {
            string keysequence = Microsoft.VisualBasic.Interaction.InputBox("Key Sequence:", "Custom", "");
            if (keysequence != "")
            {
                string[] items = keysequence.Split(',');
                byte[] b = { 0x00 };
                foreach (string item in items)
                {
                    b[0] = Convert.ToByte(item);
                    serialPort1.Write(b, 0, 1);
                }
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            serialPort1.Write(Clipboard.GetText());
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            string FileToExport = "";
            string selectedItem = lstDirectory.Text;
            if (selectedItem != "")
            {
                if (!selectedItem.StartsWith(LBracket))
                {
                    FileToExport = (_CurrentPath == "") ? selectedItem : _CurrentPath + "/" + selectedItem;
                }
                else
                    MessageBox.Show("Can only export files.", "Not Supported");
            }

            if (FileToExport != "")
            {
                saveFileDialog1.FileName = selectedItem;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    CloseComm();
                    Cursor.Current = Cursors.WaitCursor;
                    _ESP.GetFile(FileToExport, saveFileDialog1.FileName);
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        private void cboHelp_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadHelp();
        }

        private void btnReplaceAll_Click(object sender, EventArgs e)
        {
            ReplaceAllForm replaceAll = new ReplaceAllForm();
            if (replaceAll.ShowDialog() == DialogResult.OK)
            {
                string FindText = Decode(((TextBox)replaceAll.Controls["txtFind"]).Text);
                string ReplaceText = Decode(((TextBox)replaceAll.Controls["txtReplace"]).Text);

                if (FindText != "")
                    scintilla1.Text = scintilla1.Text.Replace(FindText, ReplaceText);
            }
        }

        #endregion

        #region Private Helper Routines

        private string Decode(string codedString)
        {
            string result = codedString;

            result = result.Replace("\\n", "\n");
            result = result.Replace("\\r", "\r");
            result = result.Replace("\\t", "\t");

            return result;
        }

        private void LoadHelp()
        {
            int current = cboHelp.SelectedIndex;
            if (current >= 0)
            {
                string link = ConfigurationManager.AppSettings["HelpLink" + (current + 1).ToString()];
                if (!link.ToLower().StartsWith("http"))
                {
                    if (link.Contains("\\"))
                        link = "file:///" + link;
                    else
                    {
                        link = "file:///" + Path.Combine(Directory.GetCurrentDirectory(), "help") + "\\" + link;
                    }
                }
                HelpForm help = new HelpForm();
                help.Text = ConfigurationManager.AppSettings["HelpTitle" + (current + 1).ToString()];
                ((WebBrowser)help.Controls["webBrowser1"]).Url = new Uri(link);
                help.Show();
            }
        }

        private void InvokeControlC()
        {
            try
            {
                //if (!serialPort1.IsOpen)
                //{
                //    serialPort1.PortName = _ESP.COMM_PORT;
                //    serialPort1.NewLine = CR;
                //    serialPort1.Open();
                //}

                if (serialPort1.IsOpen)
                {
                    byte[] b = { 0x03 };
                    serialPort1.Write(b, 0, 1);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void InvokeControlD()
        {
            try
            {
                //if (!serialPort1.IsOpen)
                //{
                //    serialPort1.PortName = _ESP.COMM_PORT;
                //    serialPort1.NewLine = CR;
                //    serialPort1.Open();
                //}

                if (serialPort1.IsOpen)
                {
                    byte[] b = { 0x04 };
                    serialPort1.Write(b, 0, 1);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void LoadHelpDropdown()
        {
            cboHelp.Items.Clear();
            int count = Convert.ToInt32(ConfigurationManager.AppSettings["HelpLinkCount"]);
            if (count == 0)
            {
                cboHelp.Visible = false;
                btnLoadHelp.Visible = false;
            }
            else
            {
                int current = 1;
                while (current <= count)
                {
                    string title = ConfigurationManager.AppSettings["HelpTitle" + current.ToString()];
                    cboHelp.Items.Add(title);
                    current += 1;
                }
            }
        }

        private void ButtonSave()
        {
            bool doRefresh = (_CurrentFile == NEW_FILENAME);
            bool saved = DoSave();
            if (saved)
            {
                _FileDirty = false;
                if (doRefresh)
                    RefreshFileList();
            }
        }

        private bool OKToContinue()
        {
            bool result = true;

            if (_FileDirty)
            {
                DialogResult r = MessageBox.Show("File has been edited.  Do you wish to save it first?", "Confirm", MessageBoxButtons.YesNoCancel);
                if (r == DialogResult.Yes)
                    result = DoSave();
                else if (r == DialogResult.Cancel)
                    result = false;
            }

            return result;
        }

        private bool DoSave(string prefill = "")
        {
            bool result = false;

            if (_CurrentFile == NEW_FILENAME)
            {
                string justfile = prefill;
                if ((prefill.IndexOf('/') >= 0) && (prefill.LastIndexOf('/') < prefill.Length - 1))
                {
                    justfile = prefill.Substring(prefill.LastIndexOf('/') + 1);
                }
                string filename = Microsoft.VisualBasic.Interaction.InputBox("New Filename:", "Save File", justfile);
                if (filename != "")
                {
                    if (filename.IndexOf(".") > 0)
                    {
                        _CurrentFile = _CurrentPath + "/" + filename;
                        result = SaveItem();
                    }
                    else
                        MessageBox.Show("Filename must have an extension.");
                }
            }
            else
            {                
                result = SaveItem();
            }

            return result;
        }

        private void ResetNew()
        {
            scintilla1.Text = "";
            _CurrentFile = NEW_FILENAME;
            _FileDirty = false;
            lblCurrentFile.Text = _CurrentFile;
        }

        private void OpenItem()
        {
            string selectedItem = lstDirectory.Text;
            if (selectedItem != "")
            {
                if (selectedItem == LBracket + ".." + RBracket) // Go up one directory
                {
                    int lastslash = _CurrentPath.LastIndexOf("/");
                    if (lastslash == 0)
                        _CurrentPath = "";
                    else
                        _CurrentPath = _CurrentPath.Substring(0, lastslash);
                    RefreshFileList();
                }
                else if (selectedItem.Substring(0, 1) == LBracket) // Go into the directory
                {
                    _CurrentPath = _CurrentPath + "/" + selectedItem.Replace(LBracket, "").Replace(RBracket, "");
                    RefreshFileList();
                }
                else // Otherwise open the file
                {
                    _CurrentFile = (_CurrentPath == "") ? selectedItem : _CurrentPath + "/" + selectedItem;
                    string LocalFile = Path.Combine(_SessionPath, selectedItem);

                    if (EditableFile(LocalFile))
                    {
                        CloseComm();
                        Cursor.Current = Cursors.WaitCursor;
                        _ESP.GetFile(_CurrentFile, LocalFile);
                        Cursor.Current = Cursors.Default;
                        if (File.Exists(LocalFile))
                        {
                            using (StreamReader sr = new StreamReader(LocalFile))
                            {
                                string contents = sr.ReadToEnd();
                                scintilla1.Text = contents.Replace(CRLF, LF);
                            }
                            _FileDirty = false;
                            lblCurrentFile.Text = GetFileOnly(_CurrentFile);
                        }
                    }
                    else
                        MessageBox.Show("Not listed as an editable file type.  See the .config file to add more extensions.");
                }
            }
        }

        private bool SaveItem()
        {
            bool result = false;

            try
            {
                string CurrentFilename = _CurrentFile.Substring(_CurrentFile.LastIndexOf('/') + 1);

                string SaveFile = Path.Combine(_SessionPath, CurrentFilename);
                if (File.Exists(SaveFile))
                    File.Delete(SaveFile);

                string text = scintilla1.Text;
                if (text.Contains("\n"))
                    text = text.Replace("\r", "");
                else
                    text = text.Replace("\r", "\n");
                File.WriteAllText(SaveFile, text);

                CloseComm();

                Cursor.Current = Cursors.WaitCursor;

                _ESP.PutFile(SaveFile, _CurrentFile);

                Cursor.Current = Cursors.Default;

                _FileDirty = false;

                result = true;

                MessageBox.Show("File Saved.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Save Failed");
            }

            return result;
        }

        private void RefreshFileList()
        {
            lstDirectory.Items.Clear();

            if (!(_CurrentPath == "" || _CurrentPath == "/"))
                lstDirectory.Items.Add(LBracket + ".." + RBracket);

            CloseComm();

            Cursor.Current = Cursors.WaitCursor;

            List<string> dir = null;

            bool passed = false;
            try
            {
                dir = _ESP.GetDir(_CurrentPath, LBracket, RBracket);
                passed = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("RefreshFileList() Exception: " + ex.Message);
            }

            if (!passed)
            {
                Application.DoEvents();
                dir = _ESP.GetDir(_CurrentPath, LBracket, RBracket);
            }

            Cursor.Current = Cursors.Default;

            foreach (string entry in dir)
                lstDirectory.Items.Add(entry);

            lblCurrentDirectory.Text = (_CurrentPath == "") ? "/" : _CurrentPath;

            AllowEditing();
        }

        private void Backup()
        {
            Cursor.Current = Cursors.WaitCursor;

            CloseComm();

            string newBackupPath = Path.Combine(_BackupPath, DateTime.Now.ToString("ByyyyMMdd-HHmm"));
            Directory.CreateDirectory(newBackupPath);

            string BackupCommand = Path.Combine(newBackupPath, "backup.bat");
            MakeBackupScript(BackupCommand);

            string RestoreCommand = Path.Combine(newBackupPath, "restore.bat");
            MakeRestoreScript(RestoreCommand);

            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            p.StartInfo.WorkingDirectory = newBackupPath;
            p.StartInfo.FileName = BackupCommand;
            p.Start();
            p.WaitForExit();

            CleanPath(newBackupPath);

            Cursor.Current = Cursors.Default;
        }

        private void MakeBackupScript(string output)
        {
            List<string> files = new List<string>();
            addfiles("/", ref files, true);
            string msg = "";            
            foreach (string item in files)
            {
                if (item.StartsWith(LBracket))
                {
                    msg += item.Substring(1, item.Length - 2) + CRLF;
                }
                else
                {
                    if (EditableFile(item))
                    {
                        string revitem = item.Replace("/", "\\");
                        msg += "ampy -p " + _ESP.COMM_PORT + " -b " + _ESP.BAUD_RATE.ToString() + " get " + item + " " + revitem.Substring(1) + CRLF;
                    }
                }
            }
            using (StreamWriter sw = new StreamWriter(output))
            {
                sw.Write(msg);
            }
        }

        private void MakeRestoreScript(string output)
        {
            List<string> files = new List<string>();
            addfiles("/", ref files, false);
            string msg = "";
            foreach (string item in files)
            {
                if (item.StartsWith(LBracket))
                {
                    msg += "ampy -p " + _ESP.COMM_PORT + " -b " + _ESP.BAUD_RATE.ToString() + " " + item.Substring(1, item.Length - 2) + CRLF;
                }
                else
                {
                    string revitem = item.Replace("/", "\\");
                    msg += "ampy -p " + _ESP.COMM_PORT + " -b " + _ESP.BAUD_RATE.ToString() + " put " + revitem.Substring(1) + " " + item + CRLF;
                }
            }
            using (StreamWriter sw = new StreamWriter(output))
            {
                sw.Write(msg);
            }
        }

        private void addfiles(string path, ref List<string> files, bool forBackup)
        {
            List<string> items = _ESP.GetDir(path, LBracket, RBracket);
            foreach (string item in items)
                if (!item.StartsWith(LBracket))
                {
                    if (path.EndsWith("/"))
                        files.Add(path + item);
                    else
                        files.Add(path + "/" + item);
                }
            foreach (string item in items)
                if (item.StartsWith(LBracket))
                {
                    string newdir = item.Substring(1, item.Length - 2);
                    string newpath = path;
                    if (newpath.EndsWith("/"))
                        newpath += newdir;
                    else
                        newpath += "/" + newdir;

                    if (forBackup)
                    {
                        int dirCount = 0;
                        if (path != "/")
                        {
                            string[] dirs = path.Substring(1).Split('/');
                            foreach (string dir in dirs)
                                files.Add(LBracket + "cd " + dir + RBracket);
                            dirCount = dirs.Length;
                        }
                        files.Add(LBracket + "mkdir " + newdir + RBracket);
                        if (path != "/")
                        {
                            for (int i = 1; i <= dirCount; i++) 
                                files.Add(LBracket + "cd .." + RBracket);
                        }
                    }
                    else
                    {
                        files.Add(LBracket + "mkdir " + newpath.Substring(1) + RBracket);
                    }

                    addfiles(newpath, ref files, forBackup);
                }
        }

        private void CloseComm()
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                while (serialPort1.IsOpen)
                    Application.DoEvents();

                picCommStatus.BackColor = Color.Red;
                btnChangeMode.Text = "REPL";
                btnChangeMode.ForeColor = Color.Red;
            }
        }

        private void OpenComm()
        {
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.PortName = _ESP.COMM_PORT;
                    serialPort1.NewLine = CR;
                    serialPort1.Open();
                    while (!serialPort1.IsOpen)
                        Application.DoEvents();

                    if (serialPort1.IsOpen)
                    {
                        _JustOpened = true;

                        picCommStatus.BackColor = Color.Green;
                        btnChangeMode.Text = "Editor     ";
                        btnChangeMode.ForeColor = Color.Green;
                        FreezeEditing();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        public void DoUpdate(object sender, System.EventArgs e)
        {
            if (!String.IsNullOrEmpty(_readBuffer))
            {
                // remove any jibberish when opening the port
                if (_JustOpened)
                {
                    string markertext = ConfigurationManager.AppSettings["MarkerText"];
                    int goodPos = _readBuffer.IndexOf(markertext);
                    if (goodPos > 0)
                    {
                        _readBuffer = _readBuffer.Substring(goodPos);
                        _JustOpened = false;
                    }
                    else
                    {
                        _readBuffer = "";
                    }
                }

                // check that we have something to process
                if (_readBuffer != "")
                {
                    // process a single backspace
                    if (_readBuffer == "\b\u001b[K")
                    {
                        txtTerminal.SelectionStart = txtTerminal.Text.Length - 1;
                        txtTerminal.SelectionLength = 1;
                        txtTerminal.SelectedText = "";
                    }
                    else if (_readBuffer[0] == 27 && _readBuffer[1] == 91)  // else if it begins with an escape sequence...
                    {
                        string cmd = _readBuffer.Substring(2);
                        //MessageBox.Show(cmd);
                        int pos = cmd.IndexOf('D');
                        if (pos > 0)
                        {
                            string countstr = cmd.Substring(0, pos);
                            int count = Convert.ToInt16(countstr);
                            if (count > 0)
                            {
                                txtTerminal.SelectionStart = txtTerminal.Text.Length - count;
                                txtTerminal.SelectionLength = count;
                                txtTerminal.SelectedText = "";
                            }
                            string remainder = cmd.Substring(pos + 1);
                            if (remainder != "")
                            {
                                //MessageBox.Show(remainder);
                                if (remainder == "\b\u001b[K")
                                {
                                    txtTerminal.SelectionStart = txtTerminal.Text.Length - 1;
                                    txtTerminal.SelectionLength = 1;
                                    txtTerminal.SelectedText = "";
                                }
                                else
                                {
                                    if (remainder[0] == 27 && remainder[1] == 91 && remainder[2] == 75)
                                    {
                                        txtTerminal.SelectionStart = txtTerminal.Text.Length;
                                        txtTerminal.SelectionLength = 0;
                                        txtTerminal.SelectedText = remainder.Substring(3);
                                    }
                                    else
                                    {
                                        txtTerminal.AppendText(remainder);
                                        txtTerminal.SelectionStart = txtTerminal.Text.Length;
                                        txtTerminal.SelectionLength = 0;
                                        txtTerminal.ScrollToCaret();
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (cmd == "K")
                            {
                                txtTerminal.SelectionStart = txtTerminal.Text.Length - 1;
                                txtTerminal.SelectionLength = 1;
                                txtTerminal.SelectedText = "";
                            }
                            else
                                MessageBox.Show(cmd);
                        }
                    }
                    else // else it is just some text from the device
                    {
                        txtTerminal.AppendText(_readBuffer);
                        txtTerminal.SelectionStart = txtTerminal.Text.Length;
                        txtTerminal.SelectionLength = 0;
                        txtTerminal.ScrollToCaret();
                    }
                }

                // truncate the terminal buffer
                if (txtTerminal.TextLength > _bufferLimit)
                {
                    txtTerminal.Text = txtTerminal.Text.Substring(txtTerminal.TextLength - _bufferResetSize);
                }

            }
        }

        private void FreezeEditing()
        {
            btnRefresh.Enabled = false;
            btnMkdir.Enabled = false;
            btnBackup.Enabled = false;
            btnOpen.Enabled = false;
            btnNew.Enabled = false;
            btnMove.Enabled = false;
            btnDelete.Enabled = false;
            btnLoad.Enabled = false;
            btnExport.Enabled = false;
            btnSave.Enabled = false;
            btnSaveAs.Enabled = false;
            btnReplaceAll.Enabled = false;
            lstDirectory.Enabled = false;
            scintilla1.ReadOnly = true;
            //cboHelp.Enabled = false;
            //btnLoadHelp.Enabled = false;
            btnRun.Enabled = false;
        }

        private void AllowEditing()
        {
            btnRefresh.Enabled = true;
            btnMkdir.Enabled = true;
            btnBackup.Enabled = true;
            btnOpen.Enabled = true;
            btnNew.Enabled = true;
            btnMove.Enabled = true;
            btnDelete.Enabled = true;
            btnLoad.Enabled = true;
            btnExport.Enabled = true;
            btnSave.Enabled = true;
            btnSaveAs.Enabled = true;
            btnReplaceAll.Enabled = true;
            lstDirectory.Enabled = true;
            scintilla1.ReadOnly = false;
            //cboHelp.Enabled = true;
            //btnLoadHelp.Enabled = true;
            btnRun.Enabled = true;
        }

         private string GetFileOnly(string Filename)
        {
            string result = Filename;
            if (result.IndexOf("/") >= 0)
            {
                int pos = result.LastIndexOf("/");
                result = result.Substring(pos + 1);
            }
            return result;
        }

        private bool EditableFile(string Filename)
        {
            bool result = false;

            string[] extensions = _EditableExtensions.ToLower().Split(',');

            string targetExtension = Path.GetExtension(Filename).ToLower();
            if (!String.IsNullOrEmpty(targetExtension))
                targetExtension = targetExtension.Substring(1);

            foreach (string extension in extensions)
            {
                if (extension == targetExtension)
                {
                    result = true;
                    break;
                }
            }
                
            return result;
        }

        private void CleanFile(string FileToClean)
        {
            if (File.Exists(FileToClean))
            {
                string text = File.ReadAllText(FileToClean);
                if (text.Contains("\n"))
                    text = text.Replace("\r", "");
                else
                    text = text.Replace("\r", "\n");
                File.WriteAllText(FileToClean, text);
            }
        }

        private void CleanPath(string RootPath)
        {
            string[] files = Directory.GetFiles(RootPath);
            foreach (string file in files)
            {
                if (EditableFile(file))
                    CleanFile(file);
            }
            string[] dirs = Directory.GetDirectories(RootPath);
            foreach (string dir in dirs)
                CleanPath(dir);
        }

        private void ConfigureForPython(Scintilla scintilla)
        {
            // Reset the styles
            scintilla.StyleResetDefault();
            string EditorFont = ConfigurationManager.AppSettings["EditorFont"];
            if (!String.IsNullOrEmpty(EditorFont))
                scintilla.Styles[Style.Default].Font = EditorFont;
            else
                scintilla.Styles[Style.Default].Font = "Consolas";
            string EditorFontSize = ConfigurationManager.AppSettings["EditorFontSize"];
            if (!String.IsNullOrEmpty(EditorFontSize))
                scintilla.Styles[Style.Default].Size = Convert.ToInt32(EditorFontSize);
            else
                scintilla.Styles[Style.Default].Size = 10;
            scintilla.StyleClearAll(); // i.e. Apply to all

            // Set the lexer
            scintilla.Lexer = Lexer.Python;

            // Known lexer properties:
            // "tab.timmy.whinge.level",
            // "lexer.python.literals.binary",
            // "lexer.python.strings.u",
            // "lexer.python.strings.b",
            // "lexer.python.strings.over.newline",
            // "lexer.python.keywords2.no.sub.identifiers",
            // "fold.quotes.python",
            // "fold.compact",
            // "fold"

            // Some properties we like
            scintilla.SetProperty("tab.timmy.whinge.level", "1");
            scintilla.SetProperty("fold", "1");

            scintilla1.Margins[0].Width = 25;
            scintilla1.Margins[0].Type = MarginType.Number;

            // Use margin 2 for fold markers
            scintilla.Margins[2].Type = MarginType.Symbol;
            scintilla.Margins[2].Mask = Marker.MaskFolders;
            scintilla.Margins[2].Sensitive = true;
            scintilla.Margins[2].Width = 20;

            // Reset folder markers
            for (int i = Marker.FolderEnd; i <= Marker.FolderOpen; i++)
            {
                scintilla.Markers[i].SetForeColor(SystemColors.ControlLightLight);
                scintilla.Markers[i].SetBackColor(SystemColors.ControlDark);
            }

            // Style the folder markers
            scintilla.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
            scintilla.Markers[Marker.Folder].SetBackColor(SystemColors.ControlText);
            scintilla.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
            scintilla.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
            scintilla.Markers[Marker.FolderEnd].SetBackColor(SystemColors.ControlText);
            scintilla.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
            scintilla.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
            scintilla.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
            scintilla.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;

            // Enable automatic folding
            scintilla.AutomaticFold = (AutomaticFold.Show | AutomaticFold.Click | AutomaticFold.Change);

            // Set the styles
            scintilla.Styles[Style.Python.Default].ForeColor = Color.FromArgb(0x00, 0x00, 0x7F);
            scintilla.Styles[Style.Python.CommentLine].ForeColor = Color.FromArgb(0x60, 0x60, 0x60);
            scintilla.Styles[Style.Python.CommentLine].Italic = true;
            scintilla.Styles[Style.Python.Number].ForeColor = Color.FromArgb(0x00, 0x7F, 0x7F);
            scintilla.Styles[Style.Python.String].ForeColor = Color.FromArgb(0x7F, 0x00, 0x7F);
            scintilla.Styles[Style.Python.Character].ForeColor = Color.FromArgb(0x7F, 0x00, 0x7F);
            scintilla.Styles[Style.Python.Word].ForeColor = Color.FromArgb(0x00, 0x00, 0x00);
            scintilla.Styles[Style.Python.Word].Bold = true;
            scintilla.Styles[Style.Python.Triple].ForeColor = Color.FromArgb(0x7F, 0x00, 0x00);
            scintilla.Styles[Style.Python.TripleDouble].ForeColor = Color.FromArgb(0x7F, 0x00, 0x00);
            scintilla.Styles[Style.Python.ClassName].ForeColor = Color.FromArgb(0x00, 0x00, 0x7F);
            scintilla.Styles[Style.Python.ClassName].Bold = true;
            scintilla.Styles[Style.Python.DefName].ForeColor = Color.FromArgb(0x00, 0x00, 0x7F);
            scintilla.Styles[Style.Python.DefName].Bold = true;
            scintilla.Styles[Style.Python.Operator].Bold = true;
            scintilla.Styles[Style.Python.Identifier].ForeColor = Color.FromArgb(0x00, 0x00, 0x7F);
            scintilla.Styles[Style.Python.CommentBlock].ForeColor = Color.FromArgb(0x60, 0x60, 0x60);
            scintilla.Styles[Style.Python.CommentBlock].Italic = true;
            scintilla.Styles[Style.Python.StringEol].ForeColor = Color.FromArgb(0x00, 0x00, 0x7F);
            scintilla.Styles[Style.Python.StringEol].BackColor = Color.FromArgb(0xE0, 0xC0, 0xE0);
            scintilla.Styles[Style.Python.StringEol].Bold = true;
            scintilla.Styles[Style.Python.StringEol].FillLine = true;
            scintilla.Styles[Style.Python.Word2].ForeColor = Color.FromArgb(0x00, 0x00, 0x7F);
            scintilla.Styles[Style.Python.Decorator].ForeColor = Color.FromArgb(0x80, 0x50, 0x00);

            // Important for Python
            scintilla.ViewWhitespace = WhitespaceMode.VisibleAlways;

            // Keyword lists:
            // 0 "Keywords",
            // 1 "Highlighted identifiers"

            //var python2 = "and as assert break class continue def del elif else except exec finally for from global if import in is lambda not or pass print raise return try while with yield";
            var python3 = "False None True and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield";
            //var cython = "cdef cimport cpdef";

            scintilla.SetKeywords(0, python3);
            // scintilla.SetKeywords(1, "add your own keywords here");
        }


        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern int GetWindowTextLength(IntPtr hWnd);

        private string GetCaptionOfActiveWindow()
        {
            var strTitle = string.Empty;
            var handle = GetForegroundWindow();
            // Obtain the length of the text   
            var intLength = GetWindowTextLength(handle) + 1;
            var stringBuilder = new StringBuilder(intLength);
            if (GetWindowText(handle, stringBuilder, intLength) > 0)
            {
                strTitle = stringBuilder.ToString();
            }
            return strTitle;
        }

        #endregion

    }
}


<|start_filename|>AmpyFileManager/Manager.Designer.cs<|end_filename|>
﻿namespace AmpyFileManager
{
    partial class Manager
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Manager));
            this.panel1 = new System.Windows.Forms.Panel();
            this.btnExport = new System.Windows.Forms.Button();
            this.btnMove = new System.Windows.Forms.Button();
            this.btnRun = new System.Windows.Forms.Button();
            this.btnBackup = new System.Windows.Forms.Button();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.panel5 = new System.Windows.Forms.Panel();
            this.label3 = new System.Windows.Forms.Label();
            this.cboHelp = new System.Windows.Forms.ComboBox();
            this.btnLoadHelp = new System.Windows.Forms.Button();
            this.btnChangeMode = new System.Windows.Forms.Button();
            this.btnMkdir = new System.Windows.Forms.Button();
            this.btnLoad = new System.Windows.Forms.Button();
            this.btnNew = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnOpen = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.lstDirectory = new System.Windows.Forms.ListBox();
            this.panel3 = new System.Windows.Forms.Panel();
            this.lblCurrentDirectory = new System.Windows.Forms.Label();
            this.panel6 = new System.Windows.Forms.Panel();
            this.scintilla1 = new ScintillaNET.Scintilla();
            this.panel2 = new System.Windows.Forms.Panel();
            this.lblCurrentFile = new System.Windows.Forms.Label();
            this.panel10 = new System.Windows.Forms.Panel();
            this.btnReplaceAll = new System.Windows.Forms.Button();
            this.btnSaveAs = new System.Windows.Forms.Button();
            this.btnSave = new System.Windows.Forms.Button();
            this.panel9 = new System.Windows.Forms.Panel();
            this.label2 = new System.Windows.Forms.Label();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.serialPort1 = new System.IO.Ports.SerialPort(this.components);
            this.splitContainer2 = new System.Windows.Forms.SplitContainer();
            this.txtTerminal = new System.Windows.Forms.TextBox();
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.panel4 = new System.Windows.Forms.Panel();
            this.btnCustom = new System.Windows.Forms.Button();
            this.panel7 = new System.Windows.Forms.Panel();
            this.picCommStatus = new System.Windows.Forms.PictureBox();
            this.btnControlD = new System.Windows.Forms.Button();
            this.btnControlC = new System.Windows.Forms.Button();
            this.tmrCommStatus = new System.Windows.Forms.Timer(this.components);
            this.tmrRunCommand = new System.Windows.Forms.Timer(this.components);
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.panel1.SuspendLayout();
            this.panel5.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.panel3.SuspendLayout();
            this.panel6.SuspendLayout();
            this.panel2.SuspendLayout();
            this.panel10.SuspendLayout();
            this.panel9.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
            this.splitContainer2.Panel1.SuspendLayout();
            this.splitContainer2.Panel2.SuspendLayout();
            this.splitContainer2.SuspendLayout();
            this.contextMenuStrip1.SuspendLayout();
            this.panel4.SuspendLayout();
            this.panel7.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.picCommStatus)).BeginInit();
            this.SuspendLayout();
            // 
            // panel1
            // 
            this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel1.Controls.Add(this.btnExport);
            this.panel1.Controls.Add(this.btnMove);
            this.panel1.Controls.Add(this.btnRun);
            this.panel1.Controls.Add(this.btnBackup);
            this.panel1.Controls.Add(this.btnRefresh);
            this.panel1.Controls.Add(this.panel5);
            this.panel1.Controls.Add(this.btnMkdir);
            this.panel1.Controls.Add(this.btnLoad);
            this.panel1.Controls.Add(this.btnNew);
            this.panel1.Controls.Add(this.btnDelete);
            this.panel1.Controls.Add(this.btnOpen);
            this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel1.Location = new System.Drawing.Point(0, 0);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(1173, 45);
            this.panel1.TabIndex = 0;
            // 
            // btnExport
            // 
            this.btnExport.Image = ((System.Drawing.Image)(resources.GetObject("btnExport.Image")));
            this.btnExport.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnExport.Location = new System.Drawing.Point(191, 7);
            this.btnExport.Name = "btnExport";
            this.btnExport.Size = new System.Drawing.Size(67, 30);
            this.btnExport.TabIndex = 3;
            this.btnExport.Text = "Export";
            this.btnExport.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnExport.UseVisualStyleBackColor = true;
            this.btnExport.Click += new System.EventHandler(this.btnExport_Click);
            // 
            // btnMove
            // 
            this.btnMove.Image = ((System.Drawing.Image)(resources.GetObject("btnMove.Image")));
            this.btnMove.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnMove.Location = new System.Drawing.Point(326, 7);
            this.btnMove.Name = "btnMove";
            this.btnMove.Size = new System.Drawing.Size(69, 30);
            this.btnMove.TabIndex = 5;
            this.btnMove.Text = "Move";
            this.btnMove.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnMove.UseVisualStyleBackColor = true;
            this.btnMove.Click += new System.EventHandler(this.btnMove_Click);
            // 
            // btnRun
            // 
            this.btnRun.Image = ((System.Drawing.Image)(resources.GetObject("btnRun.Image")));
            this.btnRun.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnRun.Location = new System.Drawing.Point(540, 7);
            this.btnRun.Name = "btnRun";
            this.btnRun.Size = new System.Drawing.Size(51, 30);
            this.btnRun.TabIndex = 8;
            this.btnRun.Text = "Run";
            this.btnRun.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnRun.UseVisualStyleBackColor = true;
            this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
            // 
            // btnBackup
            // 
            this.btnBackup.Image = ((System.Drawing.Image)(resources.GetObject("btnBackup.Image")));
            this.btnBackup.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnBackup.Location = new System.Drawing.Point(594, 7);
            this.btnBackup.Name = "btnBackup";
            this.btnBackup.Size = new System.Drawing.Size(72, 30);
            this.btnBackup.TabIndex = 9;
            this.btnBackup.Text = "Backup";
            this.btnBackup.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnBackup.UseVisualStyleBackColor = true;
            this.btnBackup.Click += new System.EventHandler(this.btnBackup_Click);
            // 
            // btnRefresh
            // 
            this.btnRefresh.Image = ((System.Drawing.Image)(resources.GetObject("btnRefresh.Image")));
            this.btnRefresh.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnRefresh.Location = new System.Drawing.Point(469, 7);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(67, 30);
            this.btnRefresh.TabIndex = 7;
            this.btnRefresh.Text = "Refresh";
            this.btnRefresh.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnRefresh.UseVisualStyleBackColor = true;
            this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
            // 
            // panel5
            // 
            this.panel5.Controls.Add(this.label3);
            this.panel5.Controls.Add(this.cboHelp);
            this.panel5.Controls.Add(this.btnLoadHelp);
            this.panel5.Controls.Add(this.btnChangeMode);
            this.panel5.Dock = System.Windows.Forms.DockStyle.Right;
            this.panel5.Location = new System.Drawing.Point(720, 0);
            this.panel5.Name = "panel5";
            this.panel5.Size = new System.Drawing.Size(449, 41);
            this.panel5.TabIndex = 7;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(109, 16);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(32, 13);
            this.label3.TabIndex = 13;
            this.label3.Text = "Help:";
            // 
            // cboHelp
            // 
            this.cboHelp.FormattingEnabled = true;
            this.cboHelp.Location = new System.Drawing.Point(142, 11);
            this.cboHelp.Name = "cboHelp";
            this.cboHelp.Size = new System.Drawing.Size(169, 21);
            this.cboHelp.TabIndex = 10;
            this.cboHelp.SelectedIndexChanged += new System.EventHandler(this.cboHelp_SelectedIndexChanged);
            // 
            // btnLoadHelp
            // 
            this.btnLoadHelp.Image = ((System.Drawing.Image)(resources.GetObject("btnLoadHelp.Image")));
            this.btnLoadHelp.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnLoadHelp.Location = new System.Drawing.Point(3, 5);
            this.btnLoadHelp.Name = "btnLoadHelp";
            this.btnLoadHelp.Size = new System.Drawing.Size(72, 31);
            this.btnLoadHelp.TabIndex = 11;
            this.btnLoadHelp.Text = "View...";
            this.btnLoadHelp.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnLoadHelp.UseVisualStyleBackColor = true;
            this.btnLoadHelp.Visible = false;
            this.btnLoadHelp.Click += new System.EventHandler(this.btnLoadHelp_Click);
            // 
            // btnChangeMode
            // 
            this.btnChangeMode.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnChangeMode.ForeColor = System.Drawing.Color.Red;
            this.btnChangeMode.Image = ((System.Drawing.Image)(resources.GetObject("btnChangeMode.Image")));
            this.btnChangeMode.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnChangeMode.Location = new System.Drawing.Point(327, 5);
            this.btnChangeMode.Name = "btnChangeMode";
            this.btnChangeMode.Size = new System.Drawing.Size(116, 31);
            this.btnChangeMode.TabIndex = 12;
            this.btnChangeMode.Text = "REPL";
            this.btnChangeMode.UseVisualStyleBackColor = true;
            this.btnChangeMode.Click += new System.EventHandler(this.btnChangeMode_Click);
            // 
            // btnMkdir
            // 
            this.btnMkdir.Image = ((System.Drawing.Image)(resources.GetObject("btnMkdir.Image")));
            this.btnMkdir.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnMkdir.Location = new System.Drawing.Point(398, 7);
            this.btnMkdir.Name = "btnMkdir";
            this.btnMkdir.Size = new System.Drawing.Size(68, 30);
            this.btnMkdir.TabIndex = 6;
            this.btnMkdir.Text = "MKDIR";
            this.btnMkdir.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnMkdir.UseVisualStyleBackColor = true;
            this.btnMkdir.Click += new System.EventHandler(this.btnMkdir_Click);
            // 
            // btnLoad
            // 
            this.btnLoad.Image = ((System.Drawing.Image)(resources.GetObject("btnLoad.Image")));
            this.btnLoad.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnLoad.Location = new System.Drawing.Point(129, 7);
            this.btnLoad.Name = "btnLoad";
            this.btnLoad.Size = new System.Drawing.Size(59, 30);
            this.btnLoad.TabIndex = 2;
            this.btnLoad.Text = "Load";
            this.btnLoad.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnLoad.UseVisualStyleBackColor = true;
            this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);
            // 
            // btnNew
            // 
            this.btnNew.Image = ((System.Drawing.Image)(resources.GetObject("btnNew.Image")));
            this.btnNew.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnNew.Location = new System.Drawing.Point(10, 7);
            this.btnNew.Name = "btnNew";
            this.btnNew.Size = new System.Drawing.Size(54, 30);
            this.btnNew.TabIndex = 0;
            this.btnNew.Text = "New";
            this.btnNew.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnNew.UseVisualStyleBackColor = true;
            this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
            // 
            // btnDelete
            // 
            this.btnDelete.Image = ((System.Drawing.Image)(resources.GetObject("btnDelete.Image")));
            this.btnDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnDelete.Location = new System.Drawing.Point(261, 7);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(62, 30);
            this.btnDelete.TabIndex = 4;
            this.btnDelete.Text = "Delete";
            this.btnDelete.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // btnOpen
            // 
            this.btnOpen.Image = ((System.Drawing.Image)(resources.GetObject("btnOpen.Image")));
            this.btnOpen.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnOpen.Location = new System.Drawing.Point(68, 7);
            this.btnOpen.Name = "btnOpen";
            this.btnOpen.Size = new System.Drawing.Size(59, 30);
            this.btnOpen.TabIndex = 1;
            this.btnOpen.Text = "Open";
            this.btnOpen.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.btnOpen.UseVisualStyleBackColor = true;
            this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(3, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(69, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Current Path:";
            // 
            // splitContainer1
            // 
            this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer1.Location = new System.Drawing.Point(0, 0);
            this.splitContainer1.Name = "splitContainer1";
            // 
            // splitContainer1.Panel1
            // 
            this.splitContainer1.Panel1.Controls.Add(this.lstDirectory);
            this.splitContainer1.Panel1.Controls.Add(this.panel3);
            // 
            // splitContainer1.Panel2
            // 
            this.splitContainer1.Panel2.Controls.Add(this.scintilla1);
            this.splitContainer1.Panel2.Controls.Add(this.panel2);
            this.splitContainer1.Size = new System.Drawing.Size(1173, 467);
            this.splitContainer1.SplitterDistance = 257;
            this.splitContainer1.TabIndex = 1;
            // 
            // lstDirectory
            // 
            this.lstDirectory.BackColor = System.Drawing.Color.Moccasin;
            this.lstDirectory.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lstDirectory.Font = new System.Drawing.Font("Consolas", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lstDirectory.FormattingEnabled = true;
            this.lstDirectory.IntegralHeight = false;
            this.lstDirectory.ItemHeight = 22;
            this.lstDirectory.Location = new System.Drawing.Point(0, 33);
            this.lstDirectory.Name = "lstDirectory";
            this.lstDirectory.Size = new System.Drawing.Size(257, 434);
            this.lstDirectory.TabIndex = 13;
            this.lstDirectory.DoubleClick += new System.EventHandler(this.lstDirectory_DoubleClick);
            // 
            // panel3
            // 
            this.panel3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel3.Controls.Add(this.lblCurrentDirectory);
            this.panel3.Controls.Add(this.panel6);
            this.panel3.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel3.Location = new System.Drawing.Point(0, 0);
            this.panel3.Name = "panel3";
            this.panel3.Size = new System.Drawing.Size(257, 33);
            this.panel3.TabIndex = 0;
            // 
            // lblCurrentDirectory
            // 
            this.lblCurrentDirectory.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lblCurrentDirectory.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblCurrentDirectory.Location = new System.Drawing.Point(74, 0);
            this.lblCurrentDirectory.Name = "lblCurrentDirectory";
            this.lblCurrentDirectory.Size = new System.Drawing.Size(179, 29);
            this.lblCurrentDirectory.TabIndex = 3;
            this.lblCurrentDirectory.Text = "label2";
            this.lblCurrentDirectory.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // panel6
            // 
            this.panel6.Controls.Add(this.label1);
            this.panel6.Dock = System.Windows.Forms.DockStyle.Left;
            this.panel6.Location = new System.Drawing.Point(0, 0);
            this.panel6.Name = "panel6";
            this.panel6.Size = new System.Drawing.Size(74, 29);
            this.panel6.TabIndex = 2;
            // 
            // scintilla1
            // 
            this.scintilla1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.scintilla1.EolMode = ScintillaNET.Eol.Lf;
            this.scintilla1.IndentationGuides = ScintillaNET.IndentView.Real;
            this.scintilla1.Lexer = ScintillaNET.Lexer.Python;
            this.scintilla1.Location = new System.Drawing.Point(0, 33);
            this.scintilla1.Name = "scintilla1";
            this.scintilla1.Size = new System.Drawing.Size(912, 434);
            this.scintilla1.TabIndex = 14;
            this.scintilla1.TextChanged += new System.EventHandler(this.scintilla1_TextChanged);
            // 
            // panel2
            // 
            this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel2.Controls.Add(this.lblCurrentFile);
            this.panel2.Controls.Add(this.panel10);
            this.panel2.Controls.Add(this.panel9);
            this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel2.Location = new System.Drawing.Point(0, 0);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(912, 33);
            this.panel2.TabIndex = 0;
            // 
            // lblCurrentFile
            // 
            this.lblCurrentFile.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lblCurrentFile.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblCurrentFile.Location = new System.Drawing.Point(77, 0);
            this.lblCurrentFile.Name = "lblCurrentFile";
            this.lblCurrentFile.Size = new System.Drawing.Size(610, 29);
            this.lblCurrentFile.TabIndex = 8;
            this.lblCurrentFile.Text = "label2";
            this.lblCurrentFile.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // panel10
            // 
            this.panel10.Controls.Add(this.btnReplaceAll);
            this.panel10.Controls.Add(this.btnSaveAs);
            this.panel10.Controls.Add(this.btnSave);
            this.panel10.Dock = System.Windows.Forms.DockStyle.Right;
            this.panel10.Location = new System.Drawing.Point(687, 0);
            this.panel10.Name = "panel10";
            this.panel10.Size = new System.Drawing.Size(221, 29);
            this.panel10.TabIndex = 7;
            // 
            // btnReplaceAll
            // 
            this.btnReplaceAll.Location = new System.Drawing.Point(9, 4);
            this.btnReplaceAll.Name = "btnReplaceAll";
            this.btnReplaceAll.Size = new System.Drawing.Size(72, 22);
            this.btnReplaceAll.TabIndex = 17;
            this.btnReplaceAll.Text = "Replace All";
            this.btnReplaceAll.UseVisualStyleBackColor = true;
            this.btnReplaceAll.Click += new System.EventHandler(this.btnReplaceAll_Click);
            // 
            // btnSaveAs
            // 
            this.btnSaveAs.Location = new System.Drawing.Point(84, 4);
            this.btnSaveAs.Name = "btnSaveAs";
            this.btnSaveAs.Size = new System.Drawing.Size(75, 22);
            this.btnSaveAs.TabIndex = 15;
            this.btnSaveAs.Text = "Save As...";
            this.btnSaveAs.UseVisualStyleBackColor = true;
            this.btnSaveAs.Click += new System.EventHandler(this.btnSaveAs_Click);
            // 
            // btnSave
            // 
            this.btnSave.Location = new System.Drawing.Point(162, 4);
            this.btnSave.Name = "btnSave";
            this.btnSave.Size = new System.Drawing.Size(53, 22);
            this.btnSave.TabIndex = 16;
            this.btnSave.Text = "Save";
            this.btnSave.UseVisualStyleBackColor = true;
            this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
            // 
            // panel9
            // 
            this.panel9.Controls.Add(this.label2);
            this.panel9.Dock = System.Windows.Forms.DockStyle.Left;
            this.panel9.Location = new System.Drawing.Point(0, 0);
            this.panel9.Name = "panel9";
            this.panel9.Size = new System.Drawing.Size(77, 29);
            this.panel9.TabIndex = 6;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(9, 8);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(63, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = "Current File:";
            // 
            // openFileDialog1
            // 
            this.openFileDialog1.DefaultExt = "py";
            this.openFileDialog1.Filter = "All Files (*.*)|*.*|Python Files (*.py)|*.*";
            // 
            // serialPort1
            // 
            this.serialPort1.BaudRate = 115200;
            this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
            // 
            // splitContainer2
            // 
            this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer2.Location = new System.Drawing.Point(0, 45);
            this.splitContainer2.Name = "splitContainer2";
            this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
            // 
            // splitContainer2.Panel1
            // 
            this.splitContainer2.Panel1.Controls.Add(this.splitContainer1);
            // 
            // splitContainer2.Panel2
            // 
            this.splitContainer2.Panel2.Controls.Add(this.txtTerminal);
            this.splitContainer2.Panel2.Controls.Add(this.panel4);
            this.splitContainer2.Panel2.Padding = new System.Windows.Forms.Padding(5);
            this.splitContainer2.Size = new System.Drawing.Size(1173, 620);
            this.splitContainer2.SplitterDistance = 467;
            this.splitContainer2.TabIndex = 2;
            // 
            // txtTerminal
            // 
            this.txtTerminal.AcceptsTab = true;
            this.txtTerminal.BackColor = System.Drawing.Color.Black;
            this.txtTerminal.ContextMenuStrip = this.contextMenuStrip1;
            this.txtTerminal.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtTerminal.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtTerminal.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.txtTerminal.Location = new System.Drawing.Point(5, 5);
            this.txtTerminal.Multiline = true;
            this.txtTerminal.Name = "txtTerminal";
            this.txtTerminal.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtTerminal.Size = new System.Drawing.Size(1064, 139);
            this.txtTerminal.TabIndex = 0;
            this.txtTerminal.Enter += new System.EventHandler(this.txtTerminal_Enter);
            this.txtTerminal.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtTerminal_KeyDown);
            this.txtTerminal.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtTerminal_KeyPress);
            this.txtTerminal.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.txtTerminal_PreviewKeyDown);
            // 
            // contextMenuStrip1
            // 
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.pasteToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.Size = new System.Drawing.Size(103, 26);
            this.contextMenuStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.contextMenuStrip1_ItemClicked);
            // 
            // pasteToolStripMenuItem
            // 
            this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
            this.pasteToolStripMenuItem.Size = new System.Drawing.Size(102, 22);
            this.pasteToolStripMenuItem.Text = "Paste";
            // 
            // panel4
            // 
            this.panel4.Controls.Add(this.btnCustom);
            this.panel4.Controls.Add(this.panel7);
            this.panel4.Controls.Add(this.btnControlD);
            this.panel4.Controls.Add(this.btnControlC);
            this.panel4.Dock = System.Windows.Forms.DockStyle.Right;
            this.panel4.Location = new System.Drawing.Point(1069, 5);
            this.panel4.Name = "panel4";
            this.panel4.Size = new System.Drawing.Size(99, 139);
            this.panel4.TabIndex = 1;
            // 
            // btnCustom
            // 
            this.btnCustom.Location = new System.Drawing.Point(13, 62);
            this.btnCustom.Name = "btnCustom";
            this.btnCustom.Size = new System.Drawing.Size(75, 22);
            this.btnCustom.TabIndex = 17;
            this.btnCustom.Text = "Custom...";
            this.btnCustom.UseVisualStyleBackColor = true;
            this.btnCustom.Visible = false;
            this.btnCustom.Click += new System.EventHandler(this.btnCustom_Click);
            // 
            // panel7
            // 
            this.panel7.Controls.Add(this.picCommStatus);
            this.panel7.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.panel7.Location = new System.Drawing.Point(0, 105);
            this.panel7.Name = "panel7";
            this.panel7.Size = new System.Drawing.Size(99, 34);
            this.panel7.TabIndex = 16;
            // 
            // picCommStatus
            // 
            this.picCommStatus.BackColor = System.Drawing.Color.Red;
            this.picCommStatus.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.picCommStatus.Location = new System.Drawing.Point(13, 9);
            this.picCommStatus.Name = "picCommStatus";
            this.picCommStatus.Size = new System.Drawing.Size(17, 17);
            this.picCommStatus.TabIndex = 6;
            this.picCommStatus.TabStop = false;
            this.picCommStatus.Visible = false;
            // 
            // btnControlD
            // 
            this.btnControlD.Location = new System.Drawing.Point(13, 34);
            this.btnControlD.Name = "btnControlD";
            this.btnControlD.Size = new System.Drawing.Size(75, 22);
            this.btnControlD.TabIndex = 16;
            this.btnControlD.Text = "Send Ctrl-D";
            this.btnControlD.UseVisualStyleBackColor = true;
            this.btnControlD.Click += new System.EventHandler(this.btnControlD_Click);
            // 
            // btnControlC
            // 
            this.btnControlC.Location = new System.Drawing.Point(13, 6);
            this.btnControlC.Name = "btnControlC";
            this.btnControlC.Size = new System.Drawing.Size(75, 22);
            this.btnControlC.TabIndex = 15;
            this.btnControlC.Text = "Send Ctrl-C";
            this.btnControlC.UseVisualStyleBackColor = true;
            this.btnControlC.Click += new System.EventHandler(this.btnControlC_Click);
            // 
            // tmrCommStatus
            // 
            this.tmrCommStatus.Enabled = true;
            this.tmrCommStatus.Interval = 1000;
            this.tmrCommStatus.Tick += new System.EventHandler(this.tmrCommStatus_Tick);
            // 
            // tmrRunCommand
            // 
            this.tmrRunCommand.Interval = 3000;
            this.tmrRunCommand.Tick += new System.EventHandler(this.tmrRunCommand_Tick);
            // 
            // saveFileDialog1
            // 
            this.saveFileDialog1.Title = "Export File";
            // 
            // Manager
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(1173, 665);
            this.Controls.Add(this.splitContainer2);
            this.Controls.Add(this.panel1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "Manager";
            this.Text = "Ampy File Manager";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Manager_FormClosing);
            this.Load += new System.EventHandler(this.Manager_Load);
            this.panel1.ResumeLayout(false);
            this.panel5.ResumeLayout(false);
            this.panel5.PerformLayout();
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
            this.splitContainer1.ResumeLayout(false);
            this.panel3.ResumeLayout(false);
            this.panel6.ResumeLayout(false);
            this.panel6.PerformLayout();
            this.panel2.ResumeLayout(false);
            this.panel10.ResumeLayout(false);
            this.panel9.ResumeLayout(false);
            this.panel9.PerformLayout();
            this.splitContainer2.Panel1.ResumeLayout(false);
            this.splitContainer2.Panel2.ResumeLayout(false);
            this.splitContainer2.Panel2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
            this.splitContainer2.ResumeLayout(false);
            this.contextMenuStrip1.ResumeLayout(false);
            this.panel4.ResumeLayout(false);
            this.panel7.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.picCommStatus)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.SplitContainer splitContainer1;
        private System.Windows.Forms.ListBox lstDirectory;
        private System.Windows.Forms.Panel panel3;
        private ScintillaNET.Scintilla scintilla1;
        private System.Windows.Forms.Panel panel2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnOpen;
        private System.Windows.Forms.Button btnNew;
        private System.Windows.Forms.Button btnLoad;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnBackup;
        private System.Windows.Forms.OpenFileDialog openFileDialog1;
        private System.Windows.Forms.Button btnMkdir;
        private System.IO.Ports.SerialPort serialPort1;
        private System.Windows.Forms.SplitContainer splitContainer2;
        private System.Windows.Forms.TextBox txtTerminal;
        private System.Windows.Forms.Panel panel4;
        private System.Windows.Forms.Button btnControlD;
        private System.Windows.Forms.Button btnControlC;
        private System.Windows.Forms.Timer tmrCommStatus;
        private System.Windows.Forms.Button btnRefresh;
        private System.Windows.Forms.Panel panel5;
        private System.Windows.Forms.Button btnChangeMode;
        private System.Windows.Forms.Label lblCurrentDirectory;
        private System.Windows.Forms.Panel panel6;
        private System.Windows.Forms.Label lblCurrentFile;
        private System.Windows.Forms.Panel panel10;
        private System.Windows.Forms.Button btnSaveAs;
        private System.Windows.Forms.Button btnSave;
        private System.Windows.Forms.Panel panel9;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Panel panel7;
        private System.Windows.Forms.PictureBox picCommStatus;
        private System.Windows.Forms.ComboBox cboHelp;
        private System.Windows.Forms.Button btnLoadHelp;
        private System.Windows.Forms.Button btnRun;
        private System.Windows.Forms.Timer tmrRunCommand;
        private System.Windows.Forms.Button btnCustom;
        private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
        private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
        private System.Windows.Forms.Button btnMove;
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        private System.Windows.Forms.Button btnExport;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.ToolTip toolTip1;
        private System.Windows.Forms.Button btnReplaceAll;
    }
}

<|start_filename|>AmpyFileManager/RebexAboutForm.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AmpyFileManager
{
    public partial class RebexAboutForm : Form
    {
        public RebexAboutForm()
        {
            InitializeComponent();
        }

        private void lnkRebexTerminalComponent_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            HelpForm help = new HelpForm();
            help.Text = "Rebex Terminal Emulation Library";
            ((WebBrowser)help.Controls["webBrowser1"]).Url = new Uri("https://www.rebex.net/terminal-emulation.net/");
            help.Show();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}


<|start_filename|>AmpyFileManager/Properties/Settings.Designer.cs<|end_filename|>
﻿//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace AmpyFileManager.Properties {
    
    
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
        
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
        
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("500")]
        public int WindowHeight {
            get {
                return ((int)(this["WindowHeight"]));
            }
            set {
                this["WindowHeight"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("600")]
        public int WindowWidth {
            get {
                return ((int)(this["WindowWidth"]));
            }
            set {
                this["WindowWidth"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("50")]
        public int WindowTop {
            get {
                return ((int)(this["WindowTop"]));
            }
            set {
                this["WindowTop"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("50")]
        public int WindowLeft {
            get {
                return ((int)(this["WindowLeft"]));
            }
            set {
                this["WindowLeft"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("400")]
        public int REPLHeight {
            get {
                return ((int)(this["REPLHeight"]));
            }
            set {
                this["REPLHeight"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("500")]
        public int REPLWidth {
            get {
                return ((int)(this["REPLWidth"]));
            }
            set {
                this["REPLWidth"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("60")]
        public int REPLTop {
            get {
                return ((int)(this["REPLTop"]));
            }
            set {
                this["REPLTop"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("60")]
        public int REPLLeft {
            get {
                return ((int)(this["REPLLeft"]));
            }
            set {
                this["REPLLeft"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("500")]
        public int HelpHeight {
            get {
                return ((int)(this["HelpHeight"]));
            }
            set {
                this["HelpHeight"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("600")]
        public int HelpWidth {
            get {
                return ((int)(this["HelpWidth"]));
            }
            set {
                this["HelpWidth"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("50")]
        public int HelpLeft {
            get {
                return ((int)(this["HelpLeft"]));
            }
            set {
                this["HelpLeft"] = value;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("50")]
        public int HelpTop {
            get {
                return ((int)(this["HelpTop"]));
            }
            set {
                this["HelpTop"] = value;
            }
        }
    }
}


<|start_filename|>AmpyFileManager/RebexForm.Designer.cs<|end_filename|>
﻿namespace AmpyFileManager
{
    partial class RebexForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RebexForm));
            this.terminalControl1 = new Rebex.TerminalEmulation.TerminalControl();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.terminalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.resetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
            this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // terminalControl1
            // 
            this.terminalControl1.BackColor = System.Drawing.Color.BlanchedAlmond;
            this.terminalControl1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            this.terminalControl1.Cursor = System.Windows.Forms.Cursors.IBeam;
            this.terminalControl1.CursorMouse = System.Windows.Forms.Cursors.Arrow;
            this.terminalControl1.CursorText = System.Windows.Forms.Cursors.IBeam;
            this.terminalControl1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.terminalControl1.HistoryMaxLength = 256;
            this.terminalControl1.Location = new System.Drawing.Point(0, 24);
            this.terminalControl1.Name = "terminalControl1";
            this.terminalControl1.Options.ColorScheme = Rebex.TerminalEmulation.ColorScheme.Monochrome;
            this.terminalControl1.Recorder = null;
            this.terminalControl1.Size = new System.Drawing.Size(835, 502);
            this.terminalControl1.TabIndex = 0;
            // 
            // timer1
            // 
            this.timer1.Interval = 500;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // menuStrip1
            // 
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.terminalToolStripMenuItem,
            this.aboutToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(835, 24);
            this.menuStrip1.TabIndex = 1;
            this.menuStrip1.Text = "menuStrip1";
            // 
            // terminalToolStripMenuItem
            // 
            this.terminalToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.resetToolStripMenuItem,
            this.toolStripMenuItem1,
            this.closeToolStripMenuItem});
            this.terminalToolStripMenuItem.Name = "terminalToolStripMenuItem";
            this.terminalToolStripMenuItem.Size = new System.Drawing.Size(65, 20);
            this.terminalToolStripMenuItem.Text = "Terminal";
            // 
            // resetToolStripMenuItem
            // 
            this.resetToolStripMenuItem.Name = "resetToolStripMenuItem";
            this.resetToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
            this.resetToolStripMenuItem.Text = "Reset";
            this.resetToolStripMenuItem.Click += new System.EventHandler(this.resetToolStripMenuItem_Click);
            // 
            // toolStripMenuItem1
            // 
            this.toolStripMenuItem1.Name = "toolStripMenuItem1";
            this.toolStripMenuItem1.Size = new System.Drawing.Size(177, 6);
            // 
            // closeToolStripMenuItem
            // 
            this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
            this.closeToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
            this.closeToolStripMenuItem.Text = "Close";
            this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click);
            // 
            // aboutToolStripMenuItem
            // 
            this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
            this.aboutToolStripMenuItem.Size = new System.Drawing.Size(52, 20);
            this.aboutToolStripMenuItem.Text = "About";
            this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
            // 
            // REPLForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(835, 526);
            this.Controls.Add(this.terminalControl1);
            this.Controls.Add(this.menuStrip1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MainMenuStrip = this.menuStrip1;
            this.MinimizeBox = false;
            this.Name = "REPLForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "MicroPython REPL";
            this.Activated += new System.EventHandler(this.REPLForm_Activated);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.REPLForm_FormClosing);
            this.Load += new System.EventHandler(this.REPLForm_Load);
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private Rebex.TerminalEmulation.TerminalControl terminalControl1;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem terminalToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem resetToolStripMenuItem;
        private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
        private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
    }
}

<|start_filename|>AmpyFileManager/RebexAboutForm.Designer.cs<|end_filename|>
﻿namespace AmpyFileManager
{
    partial class RebexAboutForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RebexAboutForm));
            this.lnkRebexTerminalComponent = new System.Windows.Forms.LinkLabel();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.btnOK = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // lnkRebexTerminalComponent
            // 
            this.lnkRebexTerminalComponent.AutoSize = true;
            this.lnkRebexTerminalComponent.Location = new System.Drawing.Point(138, 37);
            this.lnkRebexTerminalComponent.Name = "lnkRebexTerminalComponent";
            this.lnkRebexTerminalComponent.Size = new System.Drawing.Size(130, 13);
            this.lnkRebexTerminalComponent.TabIndex = 0;
            this.lnkRebexTerminalComponent.TabStop = true;
            this.lnkRebexTerminalComponent.Text = "Rebex Terminal Emulation";
            this.lnkRebexTerminalComponent.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkRebexTerminalComponent_LinkClicked);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 13);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(388, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "This REPL serial terminal was created with the Rebex Terminal Emulation Library.";
            // 
            // textBox1
            // 
            this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.textBox1.Location = new System.Drawing.Point(16, 63);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ReadOnly = true;
            this.textBox1.Size = new System.Drawing.Size(380, 139);
            this.textBox1.TabIndex = 2;
            this.textBox1.Text = resources.GetString("textBox1.Text");
            // 
            // btnOK
            // 
            this.btnOK.Location = new System.Drawing.Point(163, 208);
            this.btnOK.Name = "btnOK";
            this.btnOK.Size = new System.Drawing.Size(75, 23);
            this.btnOK.TabIndex = 3;
            this.btnOK.Text = "OK";
            this.btnOK.UseVisualStyleBackColor = true;
            this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
            // 
            // RebexAboutForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(408, 240);
            this.Controls.Add(this.btnOK);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.lnkRebexTerminalComponent);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "RebexAboutForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "About Rebex Terminal Emulation";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.LinkLabel lnkRebexTerminalComponent;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button btnOK;
    }
}

<|start_filename|>AmpyFileManager/ESPRoutines.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Windows.Forms;

namespace AmpyFileManager
{
    public class ESPRoutines
    {
        public string COMM_PORT = "";
        public int BAUD_RATE = 115200;
        public ESPRoutines()
        {
            string[] ports = SerialPort.GetPortNames();

            List<string> goodPorts = new List<string>();
            string exclusions = ConfigurationManager.AppSettings["CommPortExclusions"];
            string[] nums = exclusions.Split(',');
            foreach (string port in ports)
            {
                bool excluded = false;
                foreach (string portnum in nums)
                {
                    if (port == "COM" + portnum)
                    {
                        excluded = true;
                        break;
                    }
                }
                if (!excluded)
                    goodPorts.Add(port);
            }

            COMM_PORT = ConfigurationManager.AppSettings["CommPort"];
            if (!String.IsNullOrEmpty(COMM_PORT))
            {
                bool found = false;
                foreach (string port in goodPorts)
                {
                    if (port == COMM_PORT)
                        found = true;
                }
                if (!found)
                {
                    SelectComForm s = new SelectComForm();
                    ((ComboBox)s.Controls["cboPorts"]).Items.Clear();
                    foreach (string port in goodPorts.OrderBy(g => Convert.ToInt32(g.Substring(3))).ToArray())
                        ((ComboBox)s.Controls["cboPorts"]).Items.Add(port);
                    s.ShowDialog();
                    COMM_PORT = s.SELECTED_COMM_PORT;
                    s.Dispose();
                }
            }
            else
            {
                if (goodPorts.Count() == 1)
                    COMM_PORT = goodPorts[0];
                else
                {
                    SelectComForm s = new SelectComForm();
                    ((ComboBox)s.Controls["cboPorts"]).Items.Clear();
                    foreach (string port in goodPorts.OrderBy(g => Convert.ToInt32(g.Substring(3))).ToArray())
                        ((ComboBox)s.Controls["cboPorts"]).Items.Add(port);
                    s.ShowDialog();
                    COMM_PORT = s.SELECTED_COMM_PORT;
                    s.Dispose();
                }
            }

            string baudratestr = ConfigurationManager.AppSettings["BaudRate"];
            if (baudratestr != "")
                BAUD_RATE = Convert.ToInt32(baudratestr);
        }

        public void PutFile(string SrcFile, string DstFile)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "ampy";
            p.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " put \"" + SrcFile + "\" " + DstFile;
            p.Start();
            p.WaitForExit();
        }

        public void GetFile(string espfile, string localfile)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.FileName = "ampy";
            p.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " get " + espfile + " \"" + localfile + "\"";
            p.Start();
            string errors = p.StandardError.ReadToEnd();
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
        }

        public void MoveFile(string SrcFile, string DestFile)
        {
            string tmpFile = Path.GetTempFileName();
            GetFile(SrcFile, tmpFile);
            DeleteFile(SrcFile);
            PutFile(tmpFile, DestFile);
        }

        public void DeleteFile(string DeleteFile)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "ampy";
            p.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " rm " + DeleteFile;
            p.Start();
            p.WaitForExit();
        }

        public void CreateDir(string NewDirectory)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "ampy";
            p.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " mkdir " + NewDirectory;
            p.Start();
            p.WaitForExit();
        }

        public void DeleteDir(string DirectoryToDelete)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "ampy";
            p.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " rmdir " + DirectoryToDelete;
            p.Start();
            p.WaitForExit();
        }

        public string GetFileText(string file)
        {
            string contents = "";

            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "ampy";
            p.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " get " + file;
            p.Start();
            contents = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            return contents.Replace("\r\r", "");
        }

        public List<string> GetDir(string path, string LB, string RB)
        {
            List<string> dir = new List<string>();

            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "ampy";
            string nav_path = ((!String.IsNullOrEmpty(path)) ? " " + path : "");
            p.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " ls -l" + nav_path;
            p.Start();
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            if (output.IndexOf("ESP module with ESP8266") > -1)
            {
                Process p2 = new Process();
                p2.StartInfo.UseShellExecute = false;
                p2.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p2.StartInfo.CreateNoWindow = true;
                p2.StartInfo.RedirectStandardOutput = true;
                p2.StartInfo.FileName = "ampy";
                p2.StartInfo.Arguments = "-p " + COMM_PORT + " -b " + BAUD_RATE.ToString() + " ls -l" + nav_path;
                p2.Start();
                output = p2.StandardOutput.ReadToEnd();
                p2.WaitForExit();
            }

            string[] entries = output.Replace("\r\n", "\t").Split('\t');

            List<string> folders = new List<string>();
            List<string> files = new List<string>();
            foreach (string entry in entries.ToList())
                if (entry != "")
                {
                    string tempstr = "";
                    string filename = "";
                    string size = "";
                    if (nav_path != "")
                        tempstr = entry.Substring(nav_path.Length - 1);
                    else
                        tempstr = entry.Substring(1);
                    int sizepos = tempstr.IndexOf(" - ");
                    if (sizepos > -1)
                    {
                        filename = tempstr.Substring(0, sizepos);
                        size = tempstr.Substring(sizepos + 3);

                        if (filename.StartsWith("/"))
                            filename = filename.Substring(1);

                        if (filename.IndexOf(".") == -1)
                        {
                            folders.Add(filename);
                            if (!(size.StartsWith("0 bytes") || size.StartsWith("10 bytes")))
                                Debug.WriteLine("Folder <" + filename + "> has a file size of <" + size + ">.");
                        }
                        else
                            files.Add(filename);
                    }
                    else
                        Debug.WriteLine("BAD Filename :" + tempstr);
                }

            foreach (string folder in folders.OrderBy(f => f).ToList())
                dir.Add(LB + folder + RB);
            foreach (string file in files.OrderBy(f => f).ToList())
                dir.Add(file);

            return dir;
        }
        
    }
}


<|start_filename|>AmpyFileManager/RebexForm.cs<|end_filename|>
﻿using AmpyFileManager.Properties;
using Rebex.TerminalEmulation;
using System;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;

namespace AmpyFileManager
{
    public partial class RebexForm : Form
    {
        private SerialPortChannel _serialPort = null;
        private string _comPort = string.Empty;
        private int _baudRate = 115200;
        private string _command = string.Empty;
        private bool _initialized = false;

        public RebexForm(string ComPort, int BaudRate, string Command)
        {
            InitializeComponent();

            _comPort = ComPort;
            _baudRate = BaudRate;
            _command = Command;

            this.DialogResult = DialogResult.No;
        }

        private void REPLForm_Load(object sender, EventArgs e)
        {
            RestoreWindow();
        }

        private void REPLForm_Activated(object sender, EventArgs e)
        {
            if (!_initialized)
                timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            // setup font styling of terminal control
            terminalControl1.Font = new Font(ConfigurationManager.AppSettings["TerminalFont"], Convert.ToSingle(ConfigurationManager.AppSettings["TerminalFontSize"]), FontStyle.Bold);

            // create a new Serial port object
            _serialPort = new SerialPortChannel(_comPort, _baudRate);

            // bind the Serial port instance to the terminal console
            terminalControl1.Bind(_serialPort);

            // execute any pre-defined command
            Scripting scripting = terminalControl1.Scripting;
            scripting.Send("\r");
            if (!String.IsNullOrEmpty(_command))
                scripting.Send(_command + "\r");

            _initialized = true;
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Yes;
            this.Close();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RebexAboutForm aboutForm = new RebexAboutForm();
            aboutForm.ShowDialog();
        }

        private void REPLForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            terminalControl1.Unbind();
            SaveWindow();
        }

        private void RestoreWindow()
        {
            Width = Settings.Default.REPLWidth;
            Height = Settings.Default.REPLHeight;
            Top = Settings.Default.REPLTop < 0 ? 0 : Settings.Default.REPLTop;
            Left = Settings.Default.REPLLeft < 0 ? 0 : Settings.Default.REPLLeft;
        }

        private void SaveWindow()
        {
            Settings.Default.REPLHeight = Height;
            Settings.Default.REPLWidth = Width;
            Settings.Default.REPLLeft = Left;
            Settings.Default.REPLTop = Top;
            Settings.Default.Save();
        }

    }
}


<|start_filename|>AmpyFileManager/HelpForm.cs<|end_filename|>
﻿using AmpyFileManager.Properties;
using System.Windows.Forms;

namespace AmpyFileManager
{
    public partial class HelpForm : Form
    {
        public HelpForm()
        {
            InitializeComponent();
        }

        private void HelpForm_Load(object sender, System.EventArgs e)
        {
            RestoreWindow();
        }

        private void HelpForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveWindow();
        }

        private void RestoreWindow()
        {
            Width = Settings.Default.HelpWidth;
            Height = Settings.Default.HelpHeight;
            Top = Settings.Default.HelpTop < 0 ? 0 : Settings.Default.HelpTop;
            Left = Settings.Default.HelpLeft < 0 ? 0 : Settings.Default.HelpLeft;
        }

        private void SaveWindow()
        {
            Settings.Default.HelpHeight = Height;
            Settings.Default.HelpWidth = Width;
            Settings.Default.HelpLeft = Left;
            Settings.Default.HelpTop = Top;
            Settings.Default.Save();
        }

    }
}


<|start_filename|>AmpyFileManager/ReplaceAllForm.cs<|end_filename|>
﻿using System.Windows.Forms;

namespace AmpyFileManager
{
    public partial class ReplaceAllForm : Form
    {
        public ReplaceAllForm()
        {
            InitializeComponent();
        }
    }
}


<|start_filename|>AmpyFileManager/SelectComForm.cs<|end_filename|>
﻿using System;
using System.IO.Ports;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace AmpyFileManager
{
    public partial class SelectComForm : Form
    {
        public string SELECTED_COMM_PORT = "EXIT";

        public SelectComForm()
        {
            InitializeComponent();
        }

        private void SelectCom_Load(object sender, EventArgs e)
        {
            //cboPorts.Items.Clear();
            //string[] ports = SerialPort.GetPortNames().OrderBy(s => Convert.ToInt32(s.Substring(3))).ToArray();
            //foreach (string port in ports)
            //    cboPorts.Items.Add(port);
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            SELECTED_COMM_PORT = cboPorts.Text;
            this.Close();
        }

    }
}
