private static bool OK4Evaluate(HMSItem item) { bool success = ((item.Kind == DefKind.Property) || (item.Kind == DefKind.Variable)); if (!success && (item.Kind == DefKind.Function) || (item.Kind == DefKind.Method)) { success = successMethods4Eval.IndexOf("|" + item.MenuText.ToLower() + "|") >= 0; } return(success); }
private static HMSItem GetHmsItemFromLine(string line) { HMSItem item = new HMSItem(); item.Text = regexGetFromLineName.Match(line).Groups[1].Value.Trim(); item.Type = regexGetFromLineType.Match(line).Groups[1].Value.Trim(); // All ok, if not success - value is empty string item.ToolTipTitle = regexGetFromLineCmd.Match(line).Groups[1].Value.Trim(); item.ToolTipText = ""; item.MenuText = item.Text; item.Help = StylishHelp(regexGetFromLineHelp.Match(line).Groups[1].Value); if (item.ToolTipTitle.Length == 0) { item.ToolTipTitle = item.Text; if (item.Type.Length > 0) { item.ToolTipTitle += ": " + item.Type; } } return(item); }
private static void BuildAutocompleteItemsFromResourse(string file, int imageIndex, string toolTipText, AutocompleteItems itemsList, DefKind kind) { string section = ""; string filter = ""; Assembly assembly = Assembly.GetExecutingAssembly(); Stream stream = assembly.GetManifestResourceStream(file); try { using (StreamReader reader = new StreamReader(stream)) { stream = null; string line; HMSItem item = null; Match m; while ((line = reader.ReadLine()) != null) { m = Regex.Match(line, @"^\*\s*?\[(.*)\]"); if (m.Success) { section = m.Groups[1].Value.Trim(); continue; } m = Regex.Match(line, @"^\*sm\w+\s*?<(.*?)>"); if (m.Success) { filter = m.Groups[1].Value.Trim(); continue; } if (filter == "-") { continue; } if (line.StartsWith("*") || (line.Trim().Length == 0)) { continue; // Skip comments and blank lines } int indent = line.Length - line.TrimStart().Length; if (indent == 0) { item = GetHmsItemFromLine(line); item.ImageIndex = imageIndex; item.ToolTipText = toolTipText + ((section.Length > 0) ? (" (" + section + ")") : ""); item.Kind = kind; item.Filter = filter; if (kind == DefKind.Function) { item.Kind = (item.Type.Length > 0) ? DefKind.Function : DefKind.Procedure; } itemsList.Add(item); } else if ((indent == 2) || (line[0] == '\t')) { // it's help for parameters of last method if (itemsList.Count > 0) { item = itemsList[itemsList.Count - 1]; item.Params.Add(StylishHelp(line)); } } } } } catch (Exception e) { HMS.LogError(e.ToString()); } finally { if (stream != null) { stream.Dispose(); } } }
public static void InitAndLoadHMSKnowledgeDatabase() { CreateIfNotExistDirectory(WorkingDir, true); CreateIfNotExistDirectory(TemplatesDir); CreateIfNotExistDirectory(ThemesDir); // Загружаем базу данных знаний о HMS (классы, типы, функции и т.п.) из ресурсов HmsTypesString = Regex.Replace(HmsTypesStringWithHelp, "{.*?}", "").ToLower(); Assembly assembly = Assembly.GetExecutingAssembly(); HMSItem item = null; bool isStatic = false; ItemsBoolean.Add(new HMSItem() { Text = "True", ImageIndex = Images.Constant, MenuText = "True", Type = "Boolean" }); ItemsBoolean.Add(new HMSItem() { Text = "False", ImageIndex = Images.Constant, MenuText = "False", Type = "Boolean" }); Stream stream = null; try { // Load classes items stream = assembly.GetManifestResourceStream(ResourcePath + "hms_classes.txt"); using (StreamReader reader = new StreamReader(stream)) { stream = null; ClassesString = "|"; string line, name, cmd; HMSClassInfo hmsclass = null; line = reader.ReadLine(); while (line != null) { if ((line.Trim().Length < 1) || (line.StartsWith("*"))) { line = reader.ReadLine(); continue; } int indent = line.Length - line.TrimStart().Length; item = GetHmsItemFromLine(line); if (indent == 0) { // it's Class if (!HmsClasses.ContainsName(item.Text)) { hmsclass = new HMSClassInfo(); hmsclass.Name = item.Text; hmsclass.Type = item.Type; hmsclass.Help = item.Help; HmsClasses.Add(hmsclass); item.Kind = DefKind.Class; item.ImageIndex = Images.Class; item.ToolTipTitle = "Класс " + item.Text; item.IsClass = true; ItemsClass.Add(item); ClassesString += hmsclass.Name.ToLower() + "|"; } } else if (indent == 2) { // it's method or property of the class cmd = item.ToolTipTitle; if (cmd.StartsWith("function")) { item.ImageIndex = Images.Method; item.Kind = DefKind.Method; } else if (cmd.StartsWith("procedure")) { item.ImageIndex = Images.Method; item.Kind = DefKind.Procedure; } else if (cmd.StartsWith("property")) { item.ImageIndex = Images.Field; item.Kind = DefKind.Property; } else if (cmd.StartsWith("index")) { item.ImageIndex = Images.Enum; item.Kind = DefKind.Property; } else if (cmd.StartsWith("event")) { item.ImageIndex = Images.Event; item.Kind = DefKind.Event; } name = Regex.Replace(cmd, @"^(function|procedure|property|index property|event)\s+", ""); name = Regex.Match(name, @"\w+").Value.Trim(); if (name.Length < 1) { name += " "; } item.Text = name; item.MenuText = name; if (item.ImageIndex == Images.Enum) { item.Text = name + "[^]"; } else if (item.ImageIndex == Images.Method) { if (cmd.IndexOf('(') > 0) { item.Text = name + "(^)"; } //else item.Text = name + "()"; } if (name.ToLower() == "create") { // hmm... only one static method isStatic = true; hmsclass.StaticItems.Add(item); } else { isStatic = false; hmsclass.MemberItems.Add(item); } } else if ((indent == 4) || (line[0] == '\t')) { // it's help for parameters of last method if (isStatic) { if (hmsclass.StaticItems.Count > 0) { item = hmsclass.StaticItems[hmsclass.StaticItems.Count - 1]; item.Params.Add(StylishHelp(line)); } } else { if (hmsclass.MemberItems.Count > 0) { item = hmsclass.MemberItems[hmsclass.MemberItems.Count - 1]; item.Params.Add(StylishHelp(line)); } } } line = reader.ReadLine(); } } // For each Class look the derived class and add his methods (info1) and methods of derived class of derived class (info2) foreach (var classItem in HmsClasses) { if (classItem.Type.Length == 0) { continue; // if no type - skip } HMSClassInfo info1 = HmsClasses[classItem.Type]; // get derived class if (info1.Name.Length == 0) { continue; // if no found - skip } HMSClassInfo info2 = HmsClasses[info1.Type]; // get derived class of the derived class if (info2.Name.Length > 0) { foreach (var i2 in info2.MemberItems) { if (!classItem.MemberItems.ContainsName(i2.MenuText)) { classItem.MemberItems.Add(i2); } } foreach (var i2 in info2.StaticItems) { if (!classItem.StaticItems.ContainsName(i2.MenuText)) { classItem.StaticItems.Add(i2); } } } foreach (var i1 in info1.MemberItems) { if (!classItem.MemberItems.ContainsName(i1.MenuText)) { classItem.MemberItems.Add(i1); } } foreach (var i1 in info1.StaticItems) { if (!classItem.StaticItems.ContainsName(i1.MenuText)) { classItem.StaticItems.Add(i1); } } classItem.MemberItems.SortByMenuText(); classItem.StaticItems.SortByMenuText(); } // Load a built-in Types (Enumerates) stream = assembly.GetManifestResourceStream(ResourcePath + "hms_types.txt"); using (StreamReader reader = new StreamReader(stream)) { stream = null; string line; HMSClassInfo hmsType = null; while ((line = reader.ReadLine()) != null) { if (line.StartsWith("*") || (line.Trim().Length == 0)) { continue; // Skip comments and blank lines } item = GetHmsItemFromLine(line); if (!HmsTypes.ContainsName(item.Text)) { hmsType = new HMSClassInfo(); hmsType.Name = item.Text; hmsType.Type = item.Text; hmsType.Help = item.Help; string names = Regex.Match(line, @"\((.*?)\)").Groups[1].Value; foreach (string name in names.Split(',')) { item = new HMSItem(); item.ImageIndex = Images.Enum; item.Text = name; item.MenuText = name; item.ToolTipTitle = name; item.ToolTipText = "Перечисление типа " + hmsType.Name; hmsType.MemberItems.Add(item); } HmsTypes.Add(hmsType); ClassesString += hmsType.Name.ToLower() + "|"; } } } } catch (Exception e) { HMS.LogError(e.ToString()); } finally { if (stream != null) { stream.Dispose(); } } // Load a built-in Functions and Procedures items BuildAutocompleteItemsFromResourse(ResourcePath + "hms_func.txt", Images.Procedure, "", ItemsFunction, DefKind.Function); foreach (var itemFunc in ItemsFunction) { if (itemFunc.Type.Length > 0) { itemFunc.ImageIndex = Images.Function; } } // Load a built-in Variables BuildAutocompleteItemsFromResourse(ResourcePath + "hms_vars.txt", Images.Field, "Встроенная переменная", ItemsVariable, DefKind.Variable); // Load a built-in Constants BuildAutocompleteItemsFromResourse(ResourcePath + "hms_constants.txt", Images.Enum, "Встроенная константа", ItemsConstant, DefKind.Constant); foreach (var info in HmsTypes) { foreach (var typeitem in info.MemberItems) { ItemsConstant.Add(typeitem); } } // Check the self NotFoundedType = "|"; HmsTypesString += "int|long|void|bool|float|"; foreach (var q in HmsClasses) { KnownType(q.Type); foreach (var a in q.MemberItems) { KnownType(a.Type); } } foreach (var q in ItemsFunction) { KnownType(q.Type); } foreach (var q in ItemsVariable) { KnownType(q.Type); } foreach (var q in ItemsConstant) { KnownType(q.Type); } string funcList = ""; foreach (var q in ItemsFunction) { funcList += "|" + q.MenuText; } funcList = funcList.Substring(1).Replace("|Int|", "|Int\\(|"); RegexHmsFunctions = new Regex(@"\b(" + funcList + @")\b", RegexOptions.IgnoreCase); string varsList = ""; foreach (var q in ItemsVariable) { varsList += "|" + q.MenuText; } varsList = varsList.Substring(1); RegexHmsVariables = new Regex(@"\b(" + varsList + @")\b", RegexOptions.IgnoreCase); varsList = ""; foreach (var q in ItemsConstant) { varsList += "|" + q.MenuText; } varsList = varsList.Substring(1); RegexHmsConstants = new Regex(@"\b(" + varsList + @")\b", RegexOptions.IgnoreCase); ClassesString += NotFoundedType.ToLower(); HmsTypesString += ""; }
/// <summary> /// Статическая процедура, вызываемая из MouseTimer_Task по срабатыванию MouseTimer для отображения подсказки при наведении мышкой на часть текста /// </summary> /// <param name="ActiveHMSEditor">Активный (вызвавший) элемент HMSEditor</param> public static void Task(HMSEditor ActiveHMSEditor) { if (ActiveHMSEditor.Locked) { return; } try { var Editor = ActiveHMSEditor.Editor; Point point = ActiveHMSEditor.MouseLocation; int iStartLine = ActiveHMSEditor.Editor.YtoLineIndex(0); int CharHeight = ActiveHMSEditor.Editor.CharHeight; int i = point.Y / CharHeight; int iLine = iStartLine + i; if ((iLine + 1) > ActiveHMSEditor.Editor.LinesCount) { return; } Place place = ActiveHMSEditor.PointToPlace(point); string line = Editor.Lines[iLine]; string value = ""; bool evalSelection = false; if (Editor.DebugMode && (Editor.SelectedText.Length > 2)) { Place selStart = Editor.Selection.Start; Place selEnd = Editor.Selection.End; // Если указатель мыши в области виделения, то будем вычислять выдиление evalSelection = (selStart.iLine == iLine) && (selStart.iChar >= place.iChar) && (selEnd.iChar <= iLine); } Range r = new Range(Editor, place, place); Range fragment = r.GetFragmentLookedLeft(); string text = fragment.Text.Replace("#", ""); if (text.Length == 0) { return; } HMSItem item = ActiveHMSEditor.GetHMSItemByText(text); // Поиск известного элемента HMSItem по части текста if (item != null && !string.IsNullOrEmpty(item.Text)) { point.Offset(0, Editor.CharHeight - 4); // Если идёт отладка - проверяем, мы навели на переменную или свойство объекта? if (Editor.DebugMode && (evalSelection || OK4Evaluate(item))) { if (evalSelection) { text = Editor.SelectedText; } else { // проверяем, если это index свойство - то нудно вычислять значение с переданным индексом, поэтому дополняем значением [...] if (item.ImageIndex == Images.Enum) { Match m = Regex.Match(line, text + @"\[.*?\]"); if (m.Success) { text = m.Value; } } else if (item.ImageIndex == Images.Function) { Match m = Regex.Match(line, text + @"\(.*?\)"); if (m.Success) { text = m.Value; } } // Проверяем тип объекта класса, может быть удобней представить в виде текста? (TStrings или TJsonObject) text = CheckTypeForToStringRules(item.Type, text); } // Вычсиление выражения value = ActiveHMSEditor.EvalVariableValue(text); // Внедряемся в поток - показываем вплывающее окно со значением Editor.Invoke((System.Windows.Forms.MethodInvoker) delegate { ActiveHMSEditor.ValueHint.ShowValue(Editor, value, point); }); return; } // Показываем инофрмацию о функции или переменной через ToolTip Editor.Invoke((System.Windows.Forms.MethodInvoker) delegate { var tip = Editor.ToolTip; tip.ToolTipTitle = item.ToolTipTitle; tip.Help = item.Help; tip.Value = value; tip.Show(item.ToolTipText + " ", Editor, point, 10000); }); } } catch (Exception e) { HMS.LogError(e.ToString()); } }