![]() КАТЕГОРИИ:
АстрономияБиологияГеографияДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРиторикаСоциологияСпортСтроительствоТехнологияФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника
|
Приложение 7. Пример исходного кода программы для УУМ-32⇐ ПредыдущаяСтр 16 из 16
; Программа проверки вывода многозначного положительного целого crlf: macro ld a, #13 wd #0 ld a, #10 wd #0 mend
test: start 0 +ld a, #123456789 call muldig crlf crlf +ld a, #987654321 call muldig ret
; Подпрограмма вывода многозначаного положительного целого числа ; Число следует предавать в регистре A muldig: clear r0 ld r3, #-1 push r3 ; -1 - “граница” цифр в стеке mov r2, a ; {R2} := {A} loop: ld r3, #10 ; {R3} := #10 divr r2, r3 ; {R2} /= {R3} mulr r3, r2 ; {R3} *= {R2} subr a, r3 ; В {A} лежит очередная младшая цифра add a, #48 ; В {A} лежит код этой цифры push a ; затолкнули код этой цифры в стек compr r2, r0 ; проверка {R2} на 0 jeq stPrn ; Можно переходить к выводу цифр mov a, r2 ; {A} := {R2} jmp loop ; переход к началу цикла
stPrn: ld r3, #-1 ; -1 => все цифры вытолкнуты из стека nxtDig: pop a ; вытолкнули из стека код символа цифры compr a, r3 ; проверили на -1 jeq return ; если совпало, выход wd #0 ; вывод цифры jmp nxtDig ; переход к выводу очередной цифры
return: ret ; возврат из подпрограммы
end 8.8 Приложение 8. Фрагмент исходного кода приложения «Интегрированная среда разработки для УУМ-32». Код класса главного окна.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq;
namespace UUM32IDE { /// <summary>Представляет главное окно приложения</summary> public partial class MainForm : Form { #region Внутренние структуры и классы
/// <summary>Содержит расширения различных типов файлов, используемых в среде</summary> private static class FileExtentions { /// <summary>Расширение файла, содержащего код программы на Ассемблере для УУМ-32</summary> public const string DefaultAsmExt = "uum32asm"; /// <summary>Расширение файла, содержащего код программы на Ассемблере для УУМ-32 с макросами</summary> public const string DefaultMacroAsmExt = "uum32masm"; /// <summary>Расширение файла, содержащего библиотеку макросов Ассемблера для УУМ-32</summary> public const string DefaultMacroLibExt = "uum32mlb"; /// <summary>Расширение объектного файла для компоновщика УУМ-32</summary> public const string DefaultObjExt = "uum32obj"; /// <summary>Расширение исполнимого файла для УУМ-32</summary> public const string DefaultUUMExt = "uum32"; }
/// <summary>Содержит имена узлов XML-файла настроек среды</summary> private static class XmlNodeNames { public const string Root = "UUM32IDESettings"; public const string ExternalApplicationPaths = "ExternalApplicationPaths"; public const string App = "App"; public const string Styles = "Styles"; public const string Font = "Font"; public const string TextElementStyles = "TextElementStyles"; public const string StandartElementsStyles = "StandartElementsStyles"; public const string StandartStyle = "StandartStyle"; public const string Keywords = "Keywords"; public const string KeywordsStyles = "KeywordsStyles"; public const string KeywordStyle = "KeywordStyle"; public const string Indents = "Indents"; public const string LinesNumeration = "LinesNumeration"; }
/// <summary>Содержит имена атрибутов XML-файла настроек среды</summary> private static class XmlAttributeNames { public const string Relative = "relative"; public const string Name = "name"; public const string Exe = "exe"; public const string Arguments = "arguments"; public const string Size = "size"; public const string CharSet = "charSet"; public const string BackgroundColor = "bgColor"; public const string Enabled = "enabled"; public const string ID = "id"; public const string Color = "color"; public const string Style = "style"; public const string FileName = "fileName"; public const string RunAsmBeforeShellStart = "runAsmBeforeShellStart"; public const string Command = "command"; }
/// <summary>Задает константы, определяющие виды настроек дочернего окна</summary> private enum ChildSettingsTypes { /// <summary>Настройки шрифта и отступов</summary> FontAndIndents, /// <summary>Настройки нумерации</summary> NumeratorColors }
/// <summary>Представляет структуру, хранящую информацию о внешнем приложении</summary> private struct ExternalApplicationInfo { /// <summary>Путь к исполнимому файлу внешнего приложения</summary> public string ExeFileName; /// <summary>Шаблон аргументов командной строки, передаваемой приложению при запуске</summary> public string ArgumentsMask;
/// <summary>Инициализирует поля структуры заданными значениями</summary> /// <param name="exeFileName">Путь к исполнимому файлу внешнего приложения</param> /// <param name="argsMask">Шаблон аргументов командной строки, передаваемой приложению при запуске</param> public ExternalApplicationInfo(string exeFileName, string argsMask) { this.ExeFileName = exeFileName; this.ArgumentsMask = argsMask; } }
/// <summary>Представляет структуру для хранения настроек стилей поля ввода дочернего окна</summary> private struct ChildStyleSettings { /// <summary>Основной шрифт дочерних форм</summary> public Font BaseFont; /// <summary>Следует ли использовать стили при форматировании текста</summary> public bool FontStylesEnabled; /// <summary>Список стилей оформления стандартных элементов текста программы</summary> public List<FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/> StandartElementsFontStyles; /// <summary>Список стилей оформления различных ключевых слов ассемблера</summary> public List<FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/> KeywordsFontStyles; /// <summary>Цвет фона поля ввода дочернего окна</summary> public Color BackgroundColor; /// <summary>Надо ли посылать ассемблеру команду для формирования файлов ключевых слов</summary> public bool RunAsmBeforeShellStart; /// <summary>Строка, содержащая аргумент командной строки ассемблера, служащий для формирования файлов ключевых слов</summary> public string AsmCommandlineArgument; /// <summary>Имя файла, содержащего список ключевых слов ассемблера</summary> public string KeywordsFileName; }
/// <summary>Представляет структуру для хранения списка ключевых слов и информации о стиле оформления этих ключевых слов</summary> public class KeywordListWithStyle // TODO: разобраться, почему класс, а не структура { /// <summary>Представляет структуру, хранящую ключевое слово и его описание</summary> public class KeywordWithHint { public string Keyword; public string Hint;
public KeywordWithHint(string keyword, string hint) { this.Keyword = keyword; this.Hint = hint; } }
/// <summary>Список ключевых слов c описаниями</summary> public List<KeywordWithHint> KeywordList; /// <summary>Стиль, который будет применяться к ключевым словам списка</summary> public FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/ Style;
/// <summary>Содержится ли в списке заданное ключевое слово</summary> /// <param name="keyword">Искомое ключевое слово</param> /// <returns>Boolean</returns> public bool ContainsKeyword(string keyword) { foreach (KeywordWithHint kh in this.KeywordList) { if (kh.Keyword.Equals(keyword)) return true; } return false; }
public KeywordWithHint GetKwWithHint(string keyword) { foreach (KeywordWithHint kh in this.KeywordList) { if (kh.Keyword.Equals(keyword)) return kh; } return null; } }
#endregion
#region Закрытые поля и свойства
/// <summary>Настройки стилей поля ввода дочернего окна</summary> private ChildStyleSettings childStyleSettings;
/// <summary>Имя файла настроек среды</summary> private const string settingsFileName = "IDESettings.xml";
/// <summary>Заголовок диалогового окна открытия файла с исходным кодом программы</summary> private const string openAsmFileDialogTitle = "Открыть файл";
/// <summary>Фильтр диалогового окна открытия файла с исходным кодом программы</summary> private static string asmFileFilter = string.Format("Все поддерживаемые файлы|*.{0}; *.{1}; *.{2}", FileExtentions.DefaultMacroAsmExt, FileExtentions.DefaultAsmExt, FileExtentions.DefaultMacroLibExt) + "|Исходный код программы на Ассемблере для УУМ-32|*." + FileExtentions.DefaultAsmExt + "|Исходный код программы на Макроассемблере для УУМ-32|*." + FileExtentions.DefaultMacroAsmExt + "|Библиотека макросов Ассемблера для УУМ-32|*." + FileExtentions.DefaultMacroLibExt;
/// <summary>Определяет, используется ли относительная привязка внешних приложений</summary> private bool allPathsAreRelative; // используются ли относительные пути (пути, рассчитываемые относительно исполнимого файла среды)
/// <summary>Коллекция настроек внешних приложений среды</summary> private Dictionary<string, ExternalApplicationInfo> externalApplicationInfoCollection;
/// <summary>Массив размеров отступов в дочерних формах</summary> private int[] indents;
/// <summary>Путь к исполнимому файлу среды</summary> private string selfExeFile; /// <summary>Рабочая папка среды</summary> private string selfWorkDir;
/// <summary>Номер очередной открытой формы</summary> private int curMdiNumber; /// <summary>Число открытых документов</summary> private int openedDocuments;
/// <summary>Массив имен файлов, которые надо открыть после загрузки</summary> private string[] fileNamesToOpen;
private List<KeywordListWithStyle> allKeywords;
private MDIForm.NumerationSetting childNumerationSettings; /// <summary>Задает или возвращает структуру, содержащую информацию о настройках нумерации строк текста программы</summary> private MDIForm.NumerationSetting ChildNumerationSettings { get { return this.childNumerationSettings; } set { this.childNumerationSettings = value; applyChildrenSetting(ChildSettingsTypes.NumeratorColors); } }
/// <summary>Очередь, предназначенная для промежуточного хранения данных, выводимых внешними приложениями в стандартный поток вывода</summary> private Queue<string> extAppsStdOutput; /// <summary>Очередь, предназначенная для промежуточного хранения данных, выводимых внешними приложениями в стандартный поток ошибок</summary> private Queue<string> extAppsStdError;
#endregion
/// <summary>Инициализирует новый экземпляр главного окна программы</summary> /// <param name="fileNames">Список аргументов командной строки</param> public MainForm(string[] fileNames) { InitializeComponent();
this.Enabled = false; LoadForm loadForm = new LoadForm(); loadForm.Show();
this.extAppsStdOutput = new Queue<string>(); this.extAppsStdError = new Queue<string>();
this.Width = Screen.PrimaryScreen.WorkingArea.Width * 3 / 4; this.Height = Screen.PrimaryScreen.WorkingArea.Height * 3 / 4;
this.c_leftPanel.Width = this.ClientRectangle.Width / 7; this.c_bottomPanel.Height = this.ClientRectangle.Height / 4;
this.MergeToolStripButtonAndToolStripMenuItem(this.compileStripButton, this.startCompilationToolStripMenuItem, this.startCompilationToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.runStripButton, this.compileAndRunToolStripMenuItem, this.compileAndRunToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.debugStripButton, this.debugToolStripMenuItem, this.debugToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.newToolStripButton, this.newToolStripMenuItem, this.newToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.openToolStripButton, this.openToolStripMenuItem, this.openToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.saveToolStripButton, this.saveToolStripMenuItem, this.saveToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.cutToolStripButton, this.cutToolStripMenuItem, this.cutToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.copyToolStripButton, this.copyToolStripMenuItem, this.copyToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.pasteToolStripButton, this.pasteToolStripMenuItem, this.pasteToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.undoToolStripButton, this.undoToolStripMenuItem, this.undoToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.redoToolStripButton, this.redoToolStripMenuItem, this.redoToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.commentLinesToolStripButton, this.commentLinesToolStripMenuItem, this.commentLinesToolStripMenuItem_Click); this.MergeToolStripButtonAndToolStripMenuItem(this.uncommentLinesToolStripButton, this.uncommentLinesToolStripMenuItem, this.uncommentLinesToolStripMenuItem_Click);
this.newToolStripButton.Text = "Новый файл... (" + this.newToolStripMenuItem.ShortcutKeyDisplayString + ")"; // в данном случае нужна более понятная подсказка
this.selfExeFile = Application.ExecutablePath; this.selfWorkDir = Path.GetDirectoryName(this.selfExeFile);
this.LoadSettingsFromXML();
this.curMdiNumber = 1; this.openedDocuments = 0;
this.СheckMenuItems();
this.fileNamesToOpen = fileNames;
this.c_tmrExtAppsStdOutputDequeuer.Enabled = true; // включаем таймер для опорожнения очереди потока вывода внешних приложений
loadForm.Close(); this.Enabled = true; }
/// <summary>Связывает заданную кнопку панели инструментов с заданным пунктом меню.</summary> /// <param name="button">Кнопка панели инструментов, которую следует привязать к заданному пункту меню</param> /// <param name="menuItem">Пункт меню, к которому следует привязать заданную кнопку</param> /// <param name="clickEventHandler">Обработчик события нажатия заданной кнопки</param> private void MergeToolStripButtonAndToolStripMenuItem(ToolStripButton button, ToolStripMenuItem menuItem, EventHandler clickEventHandler) { button.Image = menuItem.Image; this.LinkMenuItemAndButtonText(menuItem, button); button.Click += clickEventHandler; }
/// <summary>Синхронизирует надпись на кнопке панели инструментов с названием пункта меню</summary> /// <param name="menuItem">Пункт меню</param> /// <param name="button">Кнопка панели инструментов</param> private void LinkMenuItemAndButtonText(ToolStripMenuItem menuItem, ToolStripButton button) { button.Text = menuItem.Text; if (menuItem.ShortcutKeyDisplayString != null) { button.Text += " (" + menuItem.ShortcutKeyDisplayString + ')'; } }
private void MainForm_Load(object sender, EventArgs e) { this.viewProjectExplorerToolStripMenuItem.CheckState = CheckState.Unchecked; // окошко менеджера проектов пока бесполезно
foreach (string fn in this.fileNamesToOpen) { this.OpenFile(fn); } }
/// <summary>Возвращает список списков ключевых и подсказок слов со стилями</summary> /// <param name="fileName">Путь к XML-файлу, содержащему список ключевых слов ассемблера и подсказок к ним</param> /// <returns></returns> private List<KeywordListWithStyle> GetListOfKeywordLists(string fileName) { List<KeywordListWithStyle> result = new List<KeywordListWithStyle>(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); XmlElement xmlRoot = xmlDoc.DocumentElement;
XmlNodeList keywordListNodes = xmlRoot.SelectNodes("Keywords"); foreach (XmlNode keywordListNode in keywordListNodes) { string keywordListName = keywordListNode.Attributes["type"].Value;
// добавим корневой элемент в дерево ключевых слов this.keywordsExplorer1.TreeNodes.Add(keywordListName, keywordListName); TreeNode currentTreeNode = this.keywordsExplorer1.TreeNodes[keywordListName]; List<string> curTNNodes = new List<string>();
KeywordListWithStyle keywordListWithStyle = new KeywordListWithStyle(); XmlNodeList keywords = keywordListNode.SelectNodes("Keyword");
keywordListWithStyle.KeywordList = new List<KeywordListWithStyle.KeywordWithHint>(keywords.Count); foreach (XmlNode keyword in keywords) { string name = keyword.Attributes["name"].Value; string hint = keyword.Attributes["hint"].Value;
keywordListWithStyle.KeywordList.Add(new KeywordListWithStyle.KeywordWithHint(name, hint));
// добавим элементы в список для дерева ключевых слов curTNNodes.Add(name); // добавим элементы в словарь для отображения подсказок this.keywordsExplorer1.AddKeywordToTable(name, hint); } // добавим дочерние элементы в дерево ключевых слов curTNNodes.Sort(); foreach (string treeNode in curTNNodes) { currentTreeNode.Nodes.Add(treeNode, treeNode); }
keywordListWithStyle.Style = new FontStyleSettingsForm.TextElementStyle(keywordListName); result.Add(keywordListWithStyle); }
return result; }
/// <summary>Загружает настройки среды из XML-файла</summary> private void LoadSettingsFromXML() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(this.selfWorkDir + '\\' + settingsFileName); XmlElement xmlRoot = xmlDoc.DocumentElement;
XmlNode externalApplicationsPathsNode = xmlRoot.SelectSingleNode(XmlNodeNames.ExternalApplicationPaths); { XmlAttribute relativePathsAttr = externalApplicationsPathsNode.Attributes[XmlAttributeNames.Relative]; this.allPathsAreRelative = bool.Parse(relativePathsAttr.Value);
string[] extAppNames = Enum.GetNames(typeof(ExternalApplications)); this.externalApplicationInfoCollection = new Dictionary<string, ExternalApplicationInfo>(extAppNames.Length); //XmlNodeList appInfoNodes = externalApplicationsPathsNode.SelectNodes(XmlNodeNames.App); foreach (string extAppName in extAppNames) { string xpath = string.Format("{0}[@{1}='{2}']", XmlNodeNames.App, XmlAttributeNames.ID, extAppName); XmlNode appInfoNode = externalApplicationsPathsNode.SelectSingleNode(xpath); if (appInfoNode != null) { XmlAttributeCollection attrs = appInfoNode.Attributes; this.externalApplicationInfoCollection.Add(extAppName, new ExternalApplicationInfo(attrs[XmlAttributeNames.Exe].Value, attrs[XmlAttributeNames.Arguments].Value)); } else throw new Exception(string.Format("В файле настроек нет информации о внешнем приложении {0}", extAppName)); } }
XmlNode linesNumerationNode = xmlRoot.SelectSingleNode(XmlNodeNames.LinesNumeration); { XmlAttributeCollection linesNumerationAttributes = linesNumerationNode.Attributes; this.childNumerationSettings.NumerationEnabled = bool.Parse(linesNumerationAttributes[XmlAttributeNames.Enabled].Value); this.childNumerationSettings.ForeColor = Color.FromArgb(Convert.ToInt32(linesNumerationAttributes[XmlAttributeNames.Color].Value, 16)); this.childNumerationSettings.BackColor = Color.FromArgb(Convert.ToInt32(linesNumerationAttributes[XmlAttributeNames.BackgroundColor].Value, 16)); }
XmlNode stylesNode = xmlRoot.SelectSingleNode(XmlNodeNames.Styles); { XmlNode fontNode = stylesNode.SelectSingleNode(XmlNodeNames.Font); { XmlAttributeCollection fontAttributes = fontNode.Attributes; string fontName = fontAttributes[XmlAttributeNames.Name].Value; float fontSize = float.Parse(fontAttributes[XmlAttributeNames.Size].Value); byte fontCharSet = byte.Parse(fontAttributes[XmlAttributeNames.CharSet].Value); this.childStyleSettings.BaseFont = new Font(fontName, fontSize, FontStyle.Regular, GraphicsUnit.Point, fontCharSet);
this.childStyleSettings.BackgroundColor = Color.FromArgb(Convert.ToInt32(fontAttributes[XmlAttributeNames.BackgroundColor].Value, 16)); }
XmlNode textElementStylesNode = stylesNode.SelectSingleNode(XmlNodeNames.TextElementStyles); { XmlAttribute stylesEnabled = textElementStylesNode.Attributes[XmlAttributeNames.Enabled]; this.childStyleSettings.FontStylesEnabled = bool.Parse(stylesEnabled.Value); XmlNode standartElementsStylesNode = textElementStylesNode.SelectSingleNode(XmlNodeNames.StandartElementsStyles); { string[] stdTextElNames = Enum.GetNames(typeof(FontStyleSettingsForm.StandartTextElements)); this.childStyleSettings.StandartElementsFontStyles = new List<FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/>(FontStyleSettingsForm.GetStandartTextElementsQty()); foreach (string stdTextElName in stdTextElNames) { string xpath = string.Format("{0}[@{1}='{2}']", XmlNodeNames.StandartStyle, XmlAttributeNames.ID, stdTextElName); XmlNode standartStyleNode = standartElementsStylesNode.SelectSingleNode(xpath); if (standartStyleNode != null) { XmlAttributeCollection attrs = standartStyleNode.Attributes; this.childStyleSettings.StandartElementsFontStyles.Add(new FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/( attrs[XmlAttributeNames.Name].Value, new Font(this.childStyleSettings.BaseFont, (FontStyle)byte.Parse(attrs[XmlAttributeNames.Style].Value)), Color.FromArgb(Convert.ToInt32(attrs[XmlAttributeNames.Color].Value, 16)))); } else throw new Exception(string.Format("В файле настроек нет информации о стандартном стиле оформления для {0}", stdTextElName)); } }
XmlNode keywordsNode = textElementStylesNode.SelectSingleNode(XmlNodeNames.Keywords); { XmlAttributeCollection keywordsAttributes = keywordsNode.Attributes; this.childStyleSettings.KeywordsFileName = keywordsAttributes[XmlAttributeNames.FileName].Value; this.childStyleSettings.RunAsmBeforeShellStart = bool.Parse(keywordsAttributes[XmlAttributeNames.RunAsmBeforeShellStart].Value); this.childStyleSettings.AsmCommandlineArgument = keywordsAttributes[XmlAttributeNames.Command].Value;
if (this.childStyleSettings.RunAsmBeforeShellStart) { // при необходимости вызовем ассемблер для обновления файла ключевых слов if (this.RunExternalApplication(ExternalApplications.Compiler, this.childStyleSettings.AsmCommandlineArgument) != 0) { throw new Exception("Возникла ошибка при получении файла ключевых слов"); } } this.allKeywords = GetListOfKeywordLists(GetAbsolutePathFromCurrent(this.childStyleSettings.KeywordsFileName)); // получим список списков ключевых слов со стилями по умолчанию }
XmlNode keywordsStylesNode = textElementStylesNode.SelectSingleNode(XmlNodeNames.KeywordsStyles); { this.childStyleSettings.KeywordsFontStyles = new List<FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/>(); XmlNodeList keywordStyleNodes = keywordsStylesNode.SelectNodes(XmlNodeNames.KeywordStyle); foreach (XmlNode keywordStyleNode in keywordStyleNodes) { XmlAttributeCollection keywordStyleAttributes = keywordStyleNode.Attributes; this.childStyleSettings.KeywordsFontStyles.Add(new FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/( keywordStyleAttributes[XmlAttributeNames.Name].Value, new Font(this.childStyleSettings.BaseFont, (FontStyle)byte.Parse(keywordStyleAttributes[XmlAttributeNames.Style].Value)), Color.FromArgb(Convert.ToInt32(keywordStyleAttributes[XmlAttributeNames.Color].Value, 16)))); }
// свяжем списки ключевых слов со стилями foreach (KeywordListWithStyle keywordListWithStyle in this.allKeywords) { FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/ necessaryStyle = null; foreach (FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/ keywordFontStyle in this.childStyleSettings.KeywordsFontStyles) { if (keywordListWithStyle.Style.TextElementName == keywordFontStyle.TextElementName) { necessaryStyle = keywordFontStyle; break; } } if (necessaryStyle != null) { keywordListWithStyle.Style = necessaryStyle; } else { throw new Exception(string.Format("В файле настроек отстутствует информация о стиле оформления для ключевых слов группы \"{0}\"", keywordListWithStyle.Style.TextElementName)); } } } }
XmlNode indentsNode = stylesNode.SelectSingleNode(XmlNodeNames.Indents); { string[] strIndents = indentsNode.InnerText.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (strIndents.Length > 0) { this.indents = new int[strIndents.Length]; int i = 0; foreach (string strIndent in strIndents) { this.indents[i++] = int.Parse(strIndent); } } else { this.indents = null; } } } }
/// <summary>Сохраняет настройки среды в XML-файл</summary> private void SaveSettingsToXML() { XmlWriterSettings xmlSettings = new XmlWriterSettings(); // TODO: создать этот экземпляр в конструкторе, чтобы не создавать миллион раз при каждом сохранении xmlSettings.Indent = true; xmlSettings.IndentChars = "\t"; xmlSettings.NewLineChars = "\n";
XmlWriter writer = XmlWriter.Create(this.selfWorkDir + '\\' + settingsFileName, xmlSettings); writer.WriteStartElement(XmlNodeNames.Root); { writer.WriteStartElement(XmlNodeNames.ExternalApplicationPaths); { writer.WriteAttributeString(XmlAttributeNames.Relative, this.allPathsAreRelative.ToString()); foreach (string extAppKey in this.externalApplicationInfoCollection.Keys) { writer.WriteStartElement(XmlNodeNames.App); { writer.WriteAttributeString(XmlAttributeNames.ID, extAppKey); writer.WriteAttributeString(XmlAttributeNames.Exe, this.externalApplicationInfoCollection[extAppKey].ExeFileName); writer.WriteAttributeString(XmlAttributeNames.Arguments, this.externalApplicationInfoCollection[extAppKey].ArgumentsMask); } writer.WriteEndElement(); } } writer.WriteEndElement();
writer.WriteStartElement(XmlNodeNames.LinesNumeration); { writer.WriteAttributeString(XmlAttributeNames.Enabled, this.childNumerationSettings.NumerationEnabled.ToString()); writer.WriteAttributeString(XmlAttributeNames.Color, this.childNumerationSettings.ForeColor.ToArgb().ToString("X")); writer.WriteAttributeString(XmlAttributeNames.BackgroundColor, this.childNumerationSettings.BackColor.ToArgb().ToString("X")); } writer.WriteEndElement();
writer.WriteStartElement(XmlNodeNames.Styles); { writer.WriteStartElement(XmlNodeNames.Font); { writer.WriteAttributeString(XmlAttributeNames.Name, this.childStyleSettings.BaseFont.Name); writer.WriteAttributeString(XmlAttributeNames.Size, this.childStyleSettings.BaseFont.Size.ToString()); writer.WriteAttributeString(XmlAttributeNames.CharSet, this.childStyleSettings.BaseFont.GdiCharSet.ToString()); writer.WriteAttributeString(XmlAttributeNames.BackgroundColor, this.childStyleSettings.BackgroundColor.ToArgb().ToString("X")); } writer.WriteEndElement();
writer.WriteStartElement(XmlNodeNames.TextElementStyles); { writer.WriteAttributeString(XmlAttributeNames.Enabled, this.childStyleSettings.FontStylesEnabled.ToString()); writer.WriteStartElement(XmlNodeNames.StandartElementsStyles); { int i = 0; foreach (FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/ standartStyle in this.childStyleSettings.StandartElementsFontStyles) { writer.WriteStartElement(XmlNodeNames.StandartStyle); { writer.WriteAttributeString(XmlAttributeNames.ID, Enum.GetName(typeof(FontStyleSettingsForm.StandartTextElements), (FontStyleSettingsForm.StandartTextElements)i++)); writer.WriteAttributeString(XmlAttributeNames.Name, standartStyle.TextElementName); writer.WriteAttributeString(XmlAttributeNames.Color, standartStyle.Color.ToArgb().ToString("X")); writer.WriteAttributeString(XmlAttributeNames.Style, ((byte)standartStyle.Font.Style).ToString()); } writer.WriteEndElement(); } } writer.WriteEndElement();
writer.WriteStartElement(XmlNodeNames.Keywords); { writer.WriteAttributeString(XmlAttributeNames.FileName, this.childStyleSettings.KeywordsFileName); writer.WriteAttributeString(XmlAttributeNames.RunAsmBeforeShellStart, this.childStyleSettings.RunAsmBeforeShellStart.ToString()); writer.WriteAttributeString(XmlAttributeNames.Command, this.childStyleSettings.AsmCommandlineArgument); } writer.WriteEndElement();
writer.WriteStartElement(XmlNodeNames.KeywordsStyles); { foreach (FontStyleSettingsForm.TextElementStyle/*RichFontStyle*/ keywordStyle in this.childStyleSettings.KeywordsFontStyles) { writer.WriteStartElement(XmlNodeNames.KeywordStyle); { writer.WriteAttributeString(XmlAttributeNames.Name, keywordStyle.TextElementName); writer.WriteAttributeString(XmlAttributeNames.Color, keywordStyle.Color.ToArgb().ToString("X")); writer.WriteAttributeString(XmlAttributeNames.Style, ((byte)keywordStyle.Font.Style).ToString()); } writer.WriteEndElement(); } } writer.WriteEndElement(); } writer.WriteEndElement();
writer.WriteStartElement(XmlNodeNames.Indents); { string strIndents = string.Empty; if (this.indents != null) { foreach (int indent in this.indents) { strIndents += indent.ToString() + ' '; } strIndents = strIndents.Substring(0, strIndents.Length - 1); // убрали пробел в конце } writer.WriteValue(strIndents); } writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.Flush(); writer.Close(); }
//------------------------------------------------------------------------
/// <summary>Создает новую дочернюю форму и открывает в ней заданный файл</summary> /// <param name="fileName">Имя файла, который требуется открыть</param> private MDIForm OpenFile(string fileName) { foreach (MDIForm mdiChild in this.MdiChildren) { if (mdiChild.AssociatedFileName.Equals(fileName, StringComparison.OrdinalIgnoreCase)) { // если запрашивамый файл уже открыт в среде mdiChild.Focus(); return mdiChild; } } MDIForm mdi = this.CreateNewChild(null, fileName); // когда открываем существующий файл, расширение передавать не надо mdi.OpenFile(); return mdi; }
/// <summary>Создает новое окно редактора текста программы с заданным привязанным файлом</summary> /// <param name="fileName">Имя привязываемого файла</param> /// <returns>Возвращает ссылку на созданную форму</returns> private MDIForm CreateNewChild(string ext, string fileName = null) { string text; if (fileName != null) { text = Path.GetFileName(fileName); } else { text = string.Format("noname{0}.{1}", curMdiNumber++.ToString("00"), /*FileExtentions.DefaultAsmExt*/ext); //"noname" + curMdiNumber++.ToString("00") + "." + defaultAsmExt; }
MDIForm mdiChild = new MDIForm(text, fileName);
mdiChild.FileDragDrop += new DragEventHandler(this.MainForm_DragDrop); // TODO: осторожно!
mdiChild.FormClosing += (object sender, FormClosingEventArgs e) => { MDIForm mdiSender = (MDIForm)sender; if (mdiSender.IsChanged) { DialogResult res = MessageBox.Show(string.Format("Файл {0} был изменен. Сохранить изменения?", mdiSender.Text.Substring(0, mdiSender.Text.Length - 1)), "Выход", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); switch (res) { case System.Windows.Forms.DialogResult.Cancel: e.Cancel = true; break; case System.Windows.Forms.DialogResult.Yes: this.saveToolStripMenuItem_Click(this, new EventArgs()); break; } } };
mdiChild.FormClosed += (object sender, FormClosedEventArgs e) => { this.openedDocuments--; this.СheckMenuItems(); //TODO: разобраться, почему не гасит значки, если форму закрыть иксом this.c_txtOutput.Clear(); this.errorsDataGridView.Rows.Clear(); };
mdiChild.Activated += (object sender, EventArgs e) => { string programName = ((MDIForm)sender).ProgramName; this.saveToolStripMenuItem.Text = string.Format("Сохранить {0}", programName); this.saveAsToolStripMenuItem.Text = string.Format("Сохранить {0} как...", programName); this.closeToolStripMenuItem.Text = string.Format("Закрыть {0}", programName); this.currentFileNameToolStripStatusLabel.Text = string.Format("Редактирование файла {0}", programName); };
mdiChild.Deactivate += (object sender, EventArgs e) => { this.saveToolStripMenuItem.Text = "Сохранить"; this.saveAsToolStripMenuItem.Text = "Сохранить как..."; this.closeToolStripMenuItem.Text = "Закрыть"; this.currentFileNameToolStripStatusLabel.Text = "Нет открытых файлов"; };
mdiChild.MdiParent = this;
mdiChild.StandartElementFontStyles = this.childStyleSettings.StandartElementsFontStyles; mdiChild.AllKeywords = this.allKeywords;
mdiChild.Show();
this.openedDocuments++;
this.applyChildSettings(mdiChild); this.СheckMenuItems(); return mdiChild; }
private ProjectExplorer CreateNewProjectWindow(string fileName) { ProjectExplorer prjExplorer = new ProjectExplorer(fileName); prjExplorer.TopLevel = false; this.c_leftPanel.Controls.Add(prjExplorer); prjExplorer.Show(); prjExplorer.Location = new Point(0, 0); return prjExplorer; }
#region Обработчики событий выбора пунктов меню Файл
private void newToolStripMenuItem_Click(object sender, EventArgs e) { NewFileTypeSelector fileTypeSelector = new NewFileTypeSelector("newfile"); if (fileTypeSelector.ShowDialog() == System.Windows.Forms.DialogResult.OK) { switch (fileTypeSelector.FileType) { case NewFileTypeSelector.FileTypes.AsmFile: this.CreateNewChild(FileExtentions.DefaultAsmExt/*fileTypeSelector.FileName*/); break; case NewFileTypeSelector.FileTypes.MacroAsmFile: this.CreateNewChild(FileExtentions.DefaultMacroAsmExt); break; case NewFileTypeSelector.FileTypes.MacroLib: this.CreateNewChild(FileExtentions.DefaultMacroLibExt); break; default: break; } } }
private void newProjectToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Поддержка проектов еще не реализована"); }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog.Title = openAsmFileDialogTitle; openFileDialog.Filter = asmFileFilter; openFileDialog.Multiselect = true; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { foreach (string fName in openFileDialog.FileNames) { this.OpenFile(fName); } } }
private void saveToolStripMenuItem_Click(object sender, EventArgs e) // TODO: проверить сохранение в файл, уже открытый в оболочке { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) { if (activeChild.AssociatedFileName != null) { activeChild.SaveFile(); } else { saveAsToolStripMenuItem_Click(sender, e); } } }
private void saveToolStripMenuItem_TextChanged(object sender, EventArgs e) { this.LinkMenuItemAndButtonText(this.saveToolStripMenuItem, this.saveToolStripButton); }
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) { if (activeChild.AssociatedFileName != null) { saveFileDialog.FileName = activeChild.AssociatedFileName; } else { saveFileDialog.FileName = activeChild.ProgramName; }
saveFileDialog.Filter = asmFileFilter; if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { activeChild.AssociatedFileName = saveFileDialog.FileName;
saveToolStripMenuItem_Click(sender, e); } else { return; } } }
private void closeToolStripMenuItem_Click(object sender, EventArgs e) { // TODO: изменять Enabled'ы меню Form activeChild = this.ActiveMdiChild; if (activeChild != null) { activeChild.Close(); this.СheckMenuItems(); } }
private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); }
#endregion
#region Обработчики событий выбора пунктов меню Окно
/// <summary>Располагает дочерние окна каскадом</summary> private void cascadeToolStripMenuItem_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.Cascade); }
/// <summary>Располагает дочерние окна по горизонтали</summary> private void horizontalTitleToolStripMenuItem_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileHorizontal); }
/// <summary>Располагает дочерние окна по вертикали</summary> private void verticalTitleToolStripMenuItem_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileVertical); }
#endregion
#region Обработчики событий выбора пунктов меню Правка
private void copyToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.CopyText(); }
private void cutToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.CutText(); }
private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.PasteText(); }
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.SelectAllText(); }
private void undoToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.UndoAction(); }
private void redoToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.RedoAction(); }
private void commentLinesToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.CommentSelectedLines(); }
private void uncommentLinesToolStripMenuItem_Click(object sender, EventArgs e) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild != null) activeChild.UncommentSelectedLines(); }
#endregion
#region Обработчики событий выбора пунктов меню Вид
private void viewProjectExplorerToolStripMenuItem_CheckStateChanged(object sender, EventArgs e) { if (this.viewProjectExplorerToolStripMenuItem.Checked) { ShowPanel(this.c_leftPanel); } else { HidePanel(this.c_leftPanel); } }
private void viewOutputToolStripMenuItem_CheckStateChanged(object sender, EventArgs e) { if (this.viewOutputToolStripMenuItem.Checked) { ShowPanel(this.c_bottomPanel); } else { HidePanel(this.c_bottomPanel); } }
private void viewMainToolStripToolStripMenuItem_CheckStateChanged(object sender, EventArgs e) { if (this.viewMainToolStripToolStripMenuItem.Checked) { this.mainToolStrip.Show(); } else { this.mainToolStrip.Hide(); } }
private void viewStatusBarToolStripMenuItem_CheckStateChanged(object sender, EventArgs e) { if (this.viewStatusBarToolStripMenuItem.Checked) { this.statusStrip.Show(); } else { this.statusStrip.Hide(); } }
private void viewKeywordExplorerToolStripMenuItem_CheckStateChanged(object sender, EventArgs e) { if (this.viewKeywordExplorerToolStripMenuItem.Checked) { ShowPanel(this.c_rightPanel); } else { HidePanel(this.c_rightPanel); } }
#endregion
//-----------------------------------------------------------------------------------------------
private void columnWidthsToolStripMenuItem_Click(object sender, EventArgs e) { ColumnWidthSettingsForm widthEditor = new ColumnWidthSettingsForm(this.indents); if (widthEditor.ShowDialog() == System.Windows.Forms.DialogResult.OK) { this.indents = widthEditor.ColumnWidths; //this.saveSettings(); //this.SaveSettingsToXML(); this.applyChildrenSettings(); } widthEditor.Dispose(); }
//-----------------------------------------------------------------------------------------------
#region Методы обновления настроек дочерних форм
/// <summary>Обновляет настройки полей ввода всех дочерних форм</summary> private void applyChildrenSettings() { //this.saveSettings(/*this.selfWorkDir + '\\' + settingsFileName*/); this.SaveSettingsToXML();
foreach (MDIForm mdiChild in this.MdiChildren) { this.applyChildSettings(mdiChild); } }
/// <summary>Обновляет настройки полей ввода конкретной дочерней формы</summary> /// <param name="mdiChild">Ссылка на дочернюю форму, настройки которой следует обновить</param> private void applyChildSettings(MDIForm mdiChild) { int fontSize = (int)this.childStyleSettings.BaseFont.Size/*InPoints*/; mdiChild.TextFont = this.childStyleSettings.BaseFont; if (this.indents != null) { int[] indentsInPoints = new int[/*3*/this.indents.Length]; indentsInPoints[0] = this.indents[0] * fontSize; for (int i = 1; i < this.indents.Length; i++) { indentsInPoints[i] = this.indents[i] * fontSize + indentsInPoints[i - 1]; } mdiChild.Indents = indentsInPoints; } else { mdiChild.Indents = new int[0]; } mdiChild.StandartElementFontStyles = this.childStyleSettings.StandartElementsFontStyles; mdiChild.AllKeywords = this.allKeywords; this.applyChildSetting(ChildSettingsTypes.NumeratorColors, mdiChild); }
private void applyChildrenSetting(ChildSettingsTypes settingType) { this.SaveSettingsToXML();
foreach (MDIForm mdiChild in this.MdiChildren) { this.applyChildSetting(settingType, mdiChild); } }
private void applyChildSetting(ChildSettingsTypes settingType, MDIForm mdiChild) { switch (settingType) { case ChildSettingsTypes.NumeratorColors: mdiChild.Numerator = this.ChildNumerationSettings; break; } }
#endregion
#region Методы, предназначенные для запуска внешних приложений
/// <summary>Запускает внешнее приложение с заданными аргументами командной строки и при необходимости перенаправляет его поток вывода внутрь оболочки</summary> /// <param name="app">Тип внешенго приложения</param> /// <param name="arguments">Строка, содержащая аргументы командной строки</param> /// <param name="redirectStdOutErr">Параметр, определяющий, следует ли перенаправлять стандартный вывод приложения внутрь оболочки</param> /// <returns>Возвращает код завершения программы</returns> private int RunExternalApplication(ExternalApplications app, string arguments, bool redirectStdOutErr = false) { string extAppKey = Enum.GetName(typeof(ExternalApplications), app); string processExe = this.GetAbsolutePathFromCurrent(this.externalApplicationInfoCollection[extAppKey].ExeFileName);
ProcessManager pMan = new ProcessManager(this.Location, extAppKey, processExe, arguments, redirectStdOutErr); if (redirectStdOutErr) { pMan.OutputDataReceived += (sender, e) => this.extAppsStdOutput.Enqueue(e.Data); // не выводим сразу в c_txtOutput, т.к. это происходит медленно => некоторые данные не успевают выводиться // TODO: OUT_1 это первый вариант отслеживания вывода приложения в совокупности со строкой с комментарием OUT_2. Плюсы: отображает информацию по мере поступления. Минусы: отображает не всю информацию (если ее слишком много) // TODO: возможно, отказаться от всей этой байды с событиями и просто по завершении работы приложения брать весь его вывод в одну строку и возвращать ее (см. второй вариант). Есть мысль перенаправлять вывод только от ассемблера, а там точно не будет так уж много строк. Надо подумать. pMan.ErrorDataReceived += (sender, e) => this.extAppsStdError.Enqueue(e.Data); } DialogResult res = pMan.ShowDialog(); this.Focus();
if (redirectStdOutErr) { this.extAppsStdOutput.Enqueue(new string('-', 25) + "\r\n"); // OUT_2 просто ставим разделитель } int exitCode = pMan.ProcessExitCode; pMan.Dispose(); return exitCode; }
/// <summary>Возвращает новый System.Diagnostics.Process, связанный с заданной программой</summary> /// <param name="fileName">Имя исполнимого файла программы</param> /// <param name="args">Аргументы командной строки программы</param> /// <returns>Ссылку на процесс</returns> private System.Diagnostics.Process GetProcess(string fileName, string args) { System.Diagnostics.Process process = new System.Diagnostics.Process();
if (this.allPathsAreRelative) fileName = Path.GetFullPath(this.selfWorkDir + fileName); // GetFullPath() нужен, чтобы внутри пути не было кучи переходов вверх по дереву (записей "\.."). Программа работает и без GetFullPath(), но путь получается слишком длинным, да и непроизводительно бежать сначала вверх по папкам, а потом вниз - легче идти по конкретному пути
process.StartInfo.FileName = fileName; process.StartInfo.WorkingDirectory = Path.GetDirectoryName(fileName); process.StartInfo.Arguments = args;
return process; }
#endregion
/// <summary>Делает различные пункты меню доступными и недоступными в зависимости от текущего состояния среды</summary> private void СheckMenuItems() { this.saveToolStripMenuItem.Enabled = this.saveAsToolStripMenuItem.Enabled = this.closeToolStripMenuItem.Enabled = this.compileAndRunToolStripMenuItem.Enabled = this.debugToolStripMenuItem.Enabled = this.startCompilationToolStripMenuItem.Enabled =
this.copyToolStripMenuItem.Enabled = this.cutToolStripMenuItem.Enabled = this.pasteToolStripMenuItem.Enabled = this.selectAllToolStripMenuItem.Enabled = this.commentLinesToolStripMenuItem.Enabled = this.uncommentLinesToolStripMenuItem.Enabled = this.openedDocuments > 0;
this.newToolStripButton.Enabled = this.newToolStripMenuItem.Enabled; this.openToolStripButton.Enabled = this.openToolStripMenuItem.Enabled; this.saveToolStripButton.Enabled = this.saveToolStripMenuItem.Enabled;
this.compileStripButton.Enabled = this.startCompilationToolStripMenuItem.Enabled; this.debugStripButton.Enabled = this.debugToolStripMenuItem.Enabled; this.runStripButton.Enabled = this.compileAndRunToolStripMenuItem.Enabled;
this.cutToolStripButton.Enabled = this.cutToolStripMenuItem.Enabled; this.copyToolStripButton.Enabled = this.copyToolStripMenuItem.Enabled; this.pasteToolStripButton.Enabled = this.pasteToolStripMenuItem.Enabled; this.undoToolStripButton.Enabled = this.undoToolStripMenuItem.Enabled; this.redoToolStripButton.Enabled = this.redoToolStripMenuItem.Enabled; this.commentLinesToolStripButton.Enabled = this.commentLinesToolStripMenuItem.Enabled; this.uncommentLinesToolStripButton.Enabled = this.uncommentLinesToolStripMenuItem.Enabled; }
/// <summary>Отображает заданную панель элементов управления</summary> /// <param name="panel">Панель, которую следует отобразить</param> private void ShowPanel(Panel panel) { panel.Show(); foreach (Control control in panel.Controls) { control.Show(); } }
/// <summary>Скрывает заданную панель элементов управления</summary> /// <param name="panel">Панель, которую следует скрыть</param> private void HidePanel(Panel panel) { foreach (Control control in panel.Controls) { control.Show(); //TODO: может, все-таки, Hide()? } panel.Hide(); }
/// <summary>На основании текущей настройки типа путей среды возвращает относительный или абсолютный путь, полученный из заданного абсолютного</summary> /// <param name="path">Абсолютный путь</param> private string GetCurrentPathFromAbsolute(string path) { return (this.allPathsAreRelative)? PathFinder.GetRelativePath(this.selfExeFile, path) : path; }
/// <summary>Возвращает абсолютный путь, полученный из заданного пути текущего типа (относительного либо абсолютного)</summary> /// <param name="path">Относительный либо абсолютный путь</param> private string GetAbsolutePathFromCurrent(string path) { return PathFinder.GetAbsolutePath(this.selfExeFile, path); }
private int StartCompilation() { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild == null) { throw new Exception("Невозможно вызвать компилятор, так как ни одно окно не активно"); }
if (activeChild.IsChanged) { if (MessageBox.Show("Исходный текст программы " + activeChild.ProgramName + " был изменен. Будет выполенено сохранение текста программы. Продолжить?\nВыберите \"Нет\", если хотите вернуться и сохранить программу под другим именем", "Требуется сохранение", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No) return 1; }
this.saveToolStripMenuItem_Click(this, new EventArgs()); if (activeChild.AssociatedFileName == null) return 1; // пользователь нажал "Отмена" в диалоге сохранения нового файла
this.c_txtOutput.Text = "*** Компиляция ***\r\n"; // было: this.extAppsStdOutput.Enqueue("*** Компиляция ***"); - но надо не в очередь, а напрямую, т.к. при новой компиляции окно вывода следует очистить. Ну и сразу записали, что начали компиляцию. this.errorsDataGridView.Rows.Clear();
// приступаем к компиляции string compilerKey = Enum.GetName(typeof(ExternalApplications), ExternalApplications.Compiler); int exitCode = this.RunExternalApplication(ExternalApplications.Compiler, CLArgsMaskParser.Parse(this.externalApplicationInfoCollection[compilerKey].ArgumentsMask, activeChild.AssociatedFileName), true); if (exitCode != 0) { MessageBox.Show(string.Format("Не удалость скомпилировать {0}\nПодробности см. в окне \"Вывод\"", activeChild.ProgramName), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } return exitCode; }
private void startCompilationToolStripMenuItem_Click(object sender, EventArgs e) { this.StartCompilation(); }
private void debugToolStripMenuItem_Click(object sender, EventArgs e) { //MessageBox.Show("Заглушка запуска отладчика"); this.RunProgram(true); }
private void compileAndRunToolStripMenuItem_Click(object sender, EventArgs e) { this.RunProgram(); }
/// <summary>Запускает программу на выполнение заданном режиме</summary> /// <param name="debug">Параметр, определяющий, следует ли запускать программу в режиме отладки</param> private void RunProgram(bool debug = false) { MDIForm activeChild = (MDIForm)this.ActiveMdiChild; if (activeChild == null) { return; } int exitCode = this.StartCompilation(); if (exitCode == 0) { string linkerKey = Enum.GetName(typeof(ExternalApplications), ExternalApplications.Linker); //exitCode = this.StartProcess(this.externalApplicationInfoCollection[linkerKey].ExeFileName, CLArgsMaskParser.Parse(this.externalApplicationInfoCollection[linkerKey].ArgumentsMask, activeChild.AssociatedFileName)); //this.c_txtOutput.Text += "*** Компоновка ***\r\n"; this.extAppsStdOutput.Enqueue("*** Компоновка ***"); exitCode = this.RunExternalApplication(ExternalApplications.Linker, CLArgsMaskParser.Parse(this.externalApplicationInfoCollection[linkerKey].ArgumentsMask, activeChild.AssociatedFileName), true); if (exitCode == 0) { ExternalApplications extApp = (debug)? ExternalApplications.Debugger : ExternalApplications.UUM32; string key = Enum.GetName(typeof(ExternalApplications), extApp); //this.StartProcess(this.externalApplicationInfoCollection[uumKey].ExeFileName, CLArgsMaskParser.Parse(this.externalApplicationInfoCollection[uumKey].ArgumentsMask, activeChild.AssociatedFileName)); //this.c_txtOutput.Text += "*** Запуск ***\r\n"; this.extAppsStdOutput.Enqueue("*** Запуск ***"); exitCode = this.RunExternalApplication(extApp, CLArgsMaskParser.Parse(this.externalApplicationInfoCollection[key].ArgumentsMask, activeChild.AssociatedFileName)); if (exitCode == 0) { this.extAppsStdOutput.Enqueue("Программа успешно отработала.");//this.c_txtOutput.Text += "Программа успешно отработала."; } else { this.extAppsStdOutput.Enqueue("Программа завершила работу некорректно. Код возврата: " + exitCode);//this.c_txtOutput.Text += "Программа завершила работу некорректно."; } } else { MessageBox.Show(string.Format("Не удалость скомпоновать {0}\nПодробности см. в окне \"Вывод\"", activeChild.ProgramName), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
//-------------------------------------------------------------------------------------------------
private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBox about = new AboutBox(); about.ShowDialog(); about.Dispose(); }
private void MainForm_DragEnter(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.None; } else { e.Effect = DragDropEffects.Copy; } }
// данный обработчик обслуживает и главную форму, и дочерние private void MainForm_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { foreach (string fName in (string[])e.Data.GetData(DataFormats.FileDrop)) { if (Path.Ha
|