private static void AsyncRespCallback(IAsyncResult asyncResult) { RequestState requestState = ((RequestState)(asyncResult.AsyncState)); try { HttpWebResponse response = ((HttpWebResponse)(requestState.request.EndGetResponse(asyncResult))); if (requestState.response == null) { requestState.response = response; } requestState.TotalBytes = response.ContentLength; if (DownloadProgressChanged != null) { DownloadProgressChanged(requestState, EventArgs.Empty); } Stream stream = requestState.response.GetResponseStream(); stream.BeginRead(requestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(AsyncReadCallback), requestState); } catch (WebException e) { HMS.LogError("Ошибка асинхронного получения данных с GitHub"); HMS.LogError(e.Message + " Status: " + e.Status.ToString()); if (e.Response != null) { string resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); HMS.LogError(resp); } requestState.Close(); } catch (Exception e) { HMS.LogError(e.ToString()); requestState.Close(); } //allDone.Set(); }
private static string DownloadString(string url) { string body = ""; WebResponse response = null; StreamReader readStream = null; try { HttpWebRequest request = CreateRequest(url); response = request.GetResponse(); Stream receiveStream = response.GetResponseStream(); readStream = new StreamReader(receiveStream, Encoding.UTF8); body = readStream.ReadToEnd(); } catch (WebException e) { HMS.LogError("Ошибка получения JSON данных с GitHub: " + url); HMS.LogError("Сообщение: " + e.Message + " Status: " + e.Status.ToString()); if (e.Response != null) { string resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); HMS.LogError(resp); } } catch (Exception e) { HMS.LogError(e.ToString()); } finally { if (response != null) { response.Close(); } if (readStream != null) { readStream.Close(); } } return(body); }
private static void StartAsyncRequest(string url, RequestState requestState) { IAsyncResult result = null; try { requestState.StreamDst = File.OpenWrite(requestState.File); if (!requestState.StreamDst.CanWrite) { requestState.Close(); return; } HttpWebRequest request = CreateRequest(url); requestState.request = request; result = request.BeginGetResponse(new AsyncCallback(AsyncRespCallback), requestState); if (result != null) { ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, DefaultTimeout, true); } //allDone.WaitOne(); } catch (WebException e) { requestState.Close(); HMS.LogError("Ошибка асинхронного запроса на GitHub: " + url); HMS.LogError(e.Message + " Status: " + e.Status.ToString()); if (e.Response != null) { string resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); HMS.LogError(resp); } } catch (Exception e) { requestState.Close(); HMS.LogError(e.ToString()); } }
private static int DownloadFile(string url, string file) { int bytesProcessed = 0; Stream remoteStream = null; Stream localStream = null; WebResponse response = null; CreateFoldersOfFilePath(file); try { HttpWebRequest request = CreateRequest(url); if (request != null) { response = request.GetResponse(); if (response != null) { remoteStream = response.GetResponseStream(); localStream = File.Create(file); byte[] buffer = new byte[1024]; int bytesRead; do { bytesRead = remoteStream.Read(buffer, 0, buffer.Length); localStream.Write(buffer, 0, bytesRead); bytesProcessed += bytesRead; } while (bytesRead > 0); } } } catch (WebException e) { HMS.LogError("Ошибка получения файла с GitHub: " + url); HMS.LogError(e.Message + " Status: " + e.Status.ToString()); if (e.Response != null) { string resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); HMS.LogError(resp); } } catch (Exception e) { HMS.LogError(e.ToString()); } finally { if (response != null) { response.Close(); } if (remoteStream != null) { remoteStream.Close(); } if (localStream != null) { localStream.Close(); } } return(bytesProcessed); }
private void btnUpdate_Click(object sender, EventArgs e) { if (HMSEditor.NeedRestart && AuthenticodeTools.IsTrusted(HMSEditor.NeedCopyNewFile)) { string msg = "При перезапуске программы будет возвращён встроенный редактор.\n" + "После перезапуска, чтобы вернуться к данному альтернативному редактору, " + "достаточно закрыть окно и открыть редактирование скриптов заного. "; MessageBox.Show(msg, HMSEditor.MsgCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); HMSEditor.Exit(); // waiting 3 sek, copy new file to our path and start our executable string rargs = "/C ping 127.0.0.1 -n 3 && Copy /Y \"" + HMSEditor.NeedCopyNewFile + "\" \"" + Application.ExecutablePath + "\" && Del \"" + HMSEditor.NeedCopyNewFile + "\" && \"" + Application.ExecutablePath + "\" " + HMS.StartArgs; ProcessStartInfo Info = new ProcessStartInfo(); Info.Arguments = rargs; Info.WindowStyle = ProcessWindowStyle.Hidden; Info.CreateNoWindow = true; Info.FileName = "cmd.exe"; if (!DirIsWriteable(ExecutableDir)) { msg = "Текущая программа находится в каталоге, где нужны привилегии для записи файлов.\n" + "Будет сделан запрос на ввод имени и пароля пользователя,\n" + "который данными привилегиями обладает."; MessageBox.Show(msg, HMSEditor.MsgCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); Info.Verb = "runas"; } try { Process.Start(Info); } catch (Exception ex) { msg = "Ошибка обновления программы.\n" + "Возможно, из-за нарушения прав доступа или по какой-то другой причине.\n" + "Автоматическое обновление не произошло."; MessageBox.Show(msg, HMSEditor.MsgCaption, MessageBoxButtons.OK, MessageBoxIcon.Stop); HMS.LogError(ex.ToString()); return; } TryDeleteFile(HMS.ErrorLogFile); Application.Exit(); Close(); return; } //progress.Show(); Refresh(); btnUpdateProgram.Text = "Идёт загрузка..."; btnUpdateProgram.Enabled = false; btnUpdateTemplates.Enabled = false; GitHub.DownloadFileCompleted += new EventHandler(DownloadReleaseCallback); GitHub.DownloadProgressChanged += new EventHandler(DownloadProgressCallback); GitHub.DownloadLatestReleaseAsync(tmpFileRelease); }
private static void DownloadTemplateUpdates_Task(object state) { string info = ""; try { string lastUpdateStored = HMSEditor.Settings.Get("TemplateLastUpdate", "Common", ""); string lastUpdateDate = GitHub.GetRepoUpdatedDate(GitHubTemplates, out info); if (lastUpdateStored != lastUpdateDate) { DownloadTemplates(lastUpdateDate); } } catch (Exception e) { HMS.LogError(e.ToString()); } }
public static string MarkdownToHtml(string mdText) { string body = ""; string url = "https://api.github.com/markdown"; WebResponse response = null; StreamReader readStream = null; Stream dataStream = null; try { HttpWebRequest request = CreateRequest(url); request.Method = "POST"; string postData = "{\"text\":\"" + YamlParser.EscapeSymbols(mdText) + "\",\"mode\":\"gfm\",\"context\":\"github/gollum\"}"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); response = request.GetResponse(); Stream receiveStream = response.GetResponseStream(); readStream = new StreamReader(receiveStream, Encoding.UTF8); body = readStream.ReadToEnd(); } catch (WebException e) { HMS.LogError("Ошибка получения Markdown данных с GitHub: " + url); HMS.LogError("Сообщение: " + e.Message + " Status: " + e.Status.ToString()); if (e.Response != null) { string resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); HMS.LogError(resp); } } catch (Exception e) { HMS.LogError(e.ToString()); } finally { if (response != null) { dataStream.Close(); } if (response != null) { response.Close(); } if (readStream != null) { readStream.Close(); } } return(body); }
private void btnDelete_Click(object sender, EventArgs e) { string msg; msg = "ВНИМАНИЕ!\n" + "Программа, загруженные шаблоны, настройки и установленные темы будут УДАЛЕНЫ!\n" + "Вы уверены, что хотите удалить HMSEditor, а также папку и всё её содержимое: " + HMS.WorkingDir + "?"; DialogResult answ = MessageBox.Show(msg, HMSEditor.MsgCaption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (answ == DialogResult.Yes) { HMSEditor.Exit(); try { Directory.Delete(HMS.WorkingDir, true); } catch { } // waiting 3 sek, copy new file to our path and start our executable string rargs = "/C ping 127.0.0.1 -n 3 && Del /F \"" + Application.ExecutablePath + "\""; ProcessStartInfo Info = new ProcessStartInfo(); Info.Arguments = rargs; Info.WindowStyle = ProcessWindowStyle.Hidden; Info.CreateNoWindow = true; Info.FileName = "cmd.exe"; if (!DirIsWriteable(ExecutableDir)) { msg = "Текущая программа находится в каталоге, где нужны привилегии для удаления файлов.\n" + "Будет сделан запрос на ввод имени и пароля пользователя,\n" + "который данными привилегиями обладает."; MessageBox.Show(msg, HMSEditor.MsgCaption, MessageBoxButtons.OK, MessageBoxIcon.Information); Info.Verb = "runas"; } try { Process.Start(Info); } catch (Exception ex) { msg = "Ошибка удаления программы.\n" + "Возможно, из-за нарушения прав доступа или по какой-то другой причине.\n" + "Автоматическое удаление исполняемого файла не произошло."; MessageBox.Show(msg, HMSEditor.MsgCaption, MessageBoxButtons.OK, MessageBoxIcon.Stop); HMS.LogError(ex.ToString()); return; } TryDeleteFile(HMS.ErrorLogFile); DeleteGarbage(); Application.Exit(); Close(); return; } }
public static void LoadTemplates() { // Если уже кто-то загружает шаблоны (другой поток) - ждём максимум 4 секунды int i = 10; while (TemplatesIsLoading) { if (i-- < 0) { return; } Thread.Sleep(400); } // load templates from resource INI ini = new INI(); Assembly assembly = Assembly.GetExecutingAssembly(); Stream stream = null; try { stream = assembly.GetManifestResourceStream("HMSEditorNS.Resources.hms_templates.txt"); using (StreamReader reader = new StreamReader(stream)) { stream = null; ini.Text = reader.ReadToEnd(); } } catch (Exception e) { HMS.LogError(e.ToString()); } finally { if (stream != null) { stream.Dispose(); } } TemplatesIsLoading = true; // Говорим какбе другим потокам, которые могут обновлять в фоне: "Стапэ - идёт загрузка и установка шаблонов". foreach (var lang in new Language[] { Language.CPPScript, Language.PascalScript, Language.BasicScript, Language.JScript }) { AddTemplatesFromIni(Templates, lang, ini); LoadTemplatesFromDirectory(Templates, lang, TemplatesDir + "/" + lang); } TemplatesIsLoading = false; }
public static YamlObject LoadFromFile(string file) { YamlObject result = new YamlObject(); if (!File.Exists(file)) { file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(file)); } if (File.Exists(file)) { XmlDocument xml = new XmlDocument(); xml.XmlResolver = null; try { xml.Load(file); result = readXml(xml); } catch (Exception e) { HMS.LogError("Ошибка загрузки " + file + ". Причина: " + e.Message); } } return(result); }
internal static bool ExtractZip(string zipfile, bool excludeTopDir = false, bool deleteAfter = true) { bool success = false; try { if (File.Exists(zipfile)) { char[] separators = new char[] { '/', '\\' }; using (ZipFile zip = ZipFile.Read(zipfile)) { ZipEntry[] entries = new ZipEntry[zip.Entries.Count]; zip.Entries.CopyTo(entries, 0); for (int i = 0; i < entries.Length; i++) { var e = entries[i]; if (excludeTopDir) { string filename = e.FileName; int index = filename.IndexOfAny(separators) + 1; if (index >= filename.Length) { continue; } e.FileName = filename.Substring(index); } e.Extract(TemplatesDir, ExtractExistingFileAction.OverwriteSilently); } } success = true; if (deleteAfter) { File.Delete(zipfile); } } } catch (Exception e) { HMS.LogError(e.ToString()); } return(success); }
/// <summary> /// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException /// in case of invalid version. /// </summary> /// <param name="strA">the first version</param> /// <param name="strB">the second version</param> /// <returns>less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB</returns> public static int CompareVersions(string strA, string strB) { strA = extractOnlyVersion.Match(strA).Value.Replace(" ", "").Trim(); strB = extractOnlyVersion.Match(strB).Value.Replace(" ", "").Trim(); if (strA.Length == 0) { return(-1); } if (strB.Length == 0) { return(1); } int result = 0; try { Version vA = new Version(strA.Replace(",", ".")); Version vB = new Version(strB.Replace(",", ".")); return(vA.CompareTo(vB)); } catch (Exception e) { HMS.LogError("Ошибка сравнений версий " + strA + " и " + strB); HMS.LogError(e.ToString()); } return(result); }
static void Main(string[] args) { // Запоминаем агрументы запуска (могут понадобиться при перезапуске после обновления) HMS.StartArgs = string.Join(" ", args); // Заголовок для всех MessageBox HMSEditor.MsgCaption += " v" + Application.ProductVersion; // Класс SingleGlobalInstance используется для проверки, не запущена ли уже другая копия программы using (SingleGlobalInstance instance = new SingleGlobalInstance(1000)) { if (!instance.Success) { string msg = "HMS Editor уже запущен!\n\n" + "Завершить запущенные процессы и продолжить работу?"; DialogResult answer = MessageBox.Show(msg, HMSEditor.MsgCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (answer == DialogResult.No) { return; } CloseAllOtherHMSEditors(); instance.CreateMutex(); } // Всё норм, запускаемся. Для начала вставляем обработку события при неудачных зависимостях, а там загрузим внедрённые dll AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); try { SetAllowUnsafeHeaderParsing(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Загружаем встроенные шрифты HMS.AddFontFromResource("RobotoMono-Regular.ttf"); HMS.AddFontFromResource("Roboto-Regular.ttf"); // Заполняем базу знаний функций, классов, встроенных констант и переменных... HMS.InitAndLoadHMSKnowledgeDatabase(); HMSEditor.DebugMe = CheckKey(args, "-debugga"); if (CheckKey(args, "-givemesomemagic")) { // Запуск "тихого" режима HMSEditor.SilentMode = true; if (HMSEditor.WatchHMS()) { Application.Run(new HMSEditorAppContext()); } } else { // Запуск в обычном режиме с появлением отдельного самостоятельного окна Application.Run(new FormMain()); } // Проверяем, были ли выполнены все действия при выходе (снятие хуков и проч.) if (!HMSEditor.Exited) { HMSEditor.Exit(); } } catch (Exception e) { MessageBox.Show("Очень жаль, но работа программы невозможна.\n\n" + e.ToString(), HMSEditor.MsgCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); HMS.LogError(e.ToString()); } } }
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()); } }