Ejemplo n.º 1
0
 private void OnApplicationExit(object sender, EventArgs e)
 {
     if (!HMSEditor.Exited)
     {
         HMSEditor.Exit();
     }
 }
Ejemplo n.º 2
0
 private void checkBoxWatchHMS_CheckedChanged(object sender, EventArgs e)
 {
     if (checkBoxWatchHMS.Checked)
     {
         checkBoxWatchHMS.Checked = HMSEditor.WatchHMS();
     }
     else
     {
         HMSEditor.Exit();
     }
 }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        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;
            }
        }
Ejemplo n.º 5
0
        public static void SetTheme(HMSEditor editor, string name)
        {
            if (Dict.ContainsKey(name))
            {
                SetTheme(editor.Editor, name);
                Theme t = Dict[name];
                editor.ColorCurrentLine = t.LineHighlight;
                editor.ColorChangedLine = t.ChangedLines;

                // Для тёмных тем цвет изменённых строк меняем тоже на более тёмный
                uint icol = (uint)editor.Editor.IndentBackColor.ToArgb() & 0xFFFFFF;
                if (icol < 0x808080)
                {
                    editor.ColorChangedLine = ToColor("#024A02");
                }

                editor.btnMarkChangedLines_Click(null, EventArgs.Empty);
            }
        }
Ejemplo n.º 6
0
 public AutocompleteMenu(FastColoredTextBox tb, HMSEditor ed)
 {
     // create a new popup and add the list view to it
     AutoClose        = false;
     AutoSize         = false;
     Margin           = Padding.Empty;
     Padding          = Padding.Empty;
     BackColor        = Color.White;
     listView         = new AutocompleteListView(tb);
     host             = new ToolStripControlHost(listView);
     host.Margin      = new Padding(2, 2, 2, 2);
     host.Padding     = Padding.Empty;
     host.AutoSize    = false;
     host.AutoToolTip = false;
     CalcSize();
     base.Items.Add(host);
     listView.Parent   = this;
     SearchPattern     = @"[\{\#\w\.]";
     MinFragmentLength = 2;
 }
Ejemplo n.º 7
0
        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());
                }
            }
        }
Ejemplo n.º 8
0
        /// <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());
            }
        }