Sfall-ScriptEditor

Форк
0
238 строк · 8.0 Кб
1
using System;
2
using System.Collections.Generic;
3
using System.Windows.Forms;
4

5
using ICSharpCode.TextEditor.Document;
6

7
namespace ScriptEditor
8
{
9
    internal enum InsertAt {
10
        End   = 0,
11
        After = 1,
12
        Caret = 2
13
    }
14

15
    public partial class ProcForm : Form
16
    {
17
        private bool isCreateProcedure;
18
        private bool isSetName;
19

20
        public string CheckName { get; private set; }
21

22
        public string ProcedureName
23
        {
24
            get { return tbName.Text; }
25
        }
26

27
        internal InsertAt PlaceAt
28
        {
29
            get {
30
                if (!groupBoxProcedure.Enabled) return InsertAt.Caret;
31
                return (rbPasteAtEnd.Checked) ? InsertAt.End : InsertAt.After;
32
            }
33
        }
34

35
        public bool SetInsertAtArter
36
        {
37
            set { rbAfterSelProcedure.Checked = value; }
38
        }
39

40
        /// <summary>
41
        /// Получает установленное значение копировать ли тело процедуры.
42
        /// Включает или Выключает элемент управления.
43
        /// </summary>
44
        public bool CopyProcedure
45
        {
46
            get { return cbCopyBodyProc.Checked; }
47
            set { cbCopyBodyProc.Enabled = value; }
48
        }
49

50
        public ProcForm(string name, bool readOnly = false, bool proc = false)
51
        {
52
            InitializeComponent();
53

54
            this.isCreateProcedure = proc;
55

56
            if (proc && name != null)
57
                IncrementNumber(ref name);
58

59
            tbName.Text = name;
60
            tbName.ReadOnly = readOnly;
61
        }
62

63
        private void IncrementNumber(ref string name)
64
        {
65
            int lenName = name.Length - 1;
66
            if (Char.IsDigit(name[lenName])) {
67
                int i;
68
                for (i = lenName; i > 0; i--) {
69
                    if (!Char.IsDigit(name[i]))
70
                        break;
71
                }
72
                int numZero = lenName - i;
73
                int numb = int.Parse(name.Substring(++i));
74
                numb++;
75
                name = name.Remove(i) + numb.ToString(new string('0', numZero));
76
            }
77
        }
78

79
        private void ProcForm_Shown(object sender, EventArgs e)
80
        {
81
            if (tbName.Text.Length == 0
82
               || tbName.Text.IndexOf(' ') > -1
83
               || tbName.Text == "procedure"
84
               || tbName.Text == "begin"
85
               || tbName.Text == "end"
86
               || tbName.Text == "variable")
87
            {
88
                tbName.Text = "Example(arg0, arg1)";
89
                tbName.ForeColor = System.Drawing.Color.Gray;
90
                tbName.SelectionStart = 0;
91
            } else {
92
                isSetName = true;
93
                tbName.SelectionStart = tbName.Text.Length;
94
            }
95
            tbName.Focus();
96
            if (isCreateProcedure) tbName.Enter += tbName_Enter;
97

98
        }
99

100
        private void ProcForm_FormClosing(object sender, FormClosingEventArgs e)
101
        {
102
            if (!isSetName || DialogResult != DialogResult.OK || tbName.Text.Length == 0) return;
103

104
            tbName.Text = tbName.Text.Trim();
105
            string name = tbName.Text;
106

107
            int z = name.IndexOf('(');
108
            if (z > 0) {
109
                while (true)
110
                {
111
                    z = name.IndexOf("variable ", z, StringComparison.OrdinalIgnoreCase);
112
                    if (z == -1) break;
113
                    name = name.Remove(z, 9);
114
                }
115
            }
116
            // удаление пробелов
117
            name = name.Replace(" ", "");
118

119
            CheckName = name;
120
            z = CheckName.IndexOf('(');
121
            if (z > -1) CheckName = CheckName.Remove(z);
122

123
            // проверка корректности имени
124
            for (int i = 0; i < CheckName.Length; i++)
125
            {
126
                char ch = CheckName[i];
127
                if (!TextUtilities.IsLetterDigitOrUnderscore(ch)) {
128
                    e.Cancel = true;
129
                    break;
130
                }
131
            }
132

133
            if (isCreateProcedure && z > 0) {
134
                int pairCount = 0, pair = 0;
135
                // проверка корректности аргументов
136
                for (int i = z; i < name.Length; i++)
137
                {
138
                    char ch = name[i];
139
                    if (ch == ',') continue;
140
                    if (pair > 0 && ch == ')') pairCount++;
141
                    if (ch == '(') pair++;
142
                    if (ch == ')') pair--;
143
                    if ( ch == '(' || ch == ')') continue;
144

145
                    if (!TextUtilities.IsLetterDigitOrUnderscore(ch)) {
146
                        e.Cancel = true;
147
                        break;
148
                    }
149
                }
150
                if (pair != 0 || pairCount > 1) e.Cancel = true;
151
            }
152

153
            if (e.Cancel)
154
                MessageBox.Show("Was used incorrect name.\nThe name can only contain alphanumeric characters and the underscore character.", "Incorrect name");
155
            else {
156
                // вставляем ключевые слова 'variable' для аргументов процедуры
157
                if (z != -1) {
158
                    z++;
159
                    int y = name.LastIndexOf(')');
160
                    if (z == y) return; // no args
161

162
                    string pName = name.Substring(0, z - 1);
163

164
                    List<byte> args = new List<byte>();
165
                    for (byte i = (byte)z; i < y; i++) {
166
                        if (name[i] == ',') args.Add(i);
167
                    }
168
                    args.Add((byte)y);
169

170
                    // извлекаем имена аргументов
171
                    string argNames = string.Empty;
172
                    for (byte i = 0; i < args.Count; i++)
173
                    {
174
                        int x = args[i];
175
                        string argName = name.Substring(z, x - z).Trim();
176
                        z = x + 1;
177

178
                        if (argName.Length == 0) continue;
179

180
                        if (!argName.StartsWith("variable ")) argName = argName.Insert(0, "variable ");
181
                        if (argNames != string.Empty) argNames += ", ";
182
                        argNames += argName;
183
                    }
184
                    tbName.Text = string.Format("{0}({1})", pName, argNames);
185
                }
186
            }
187
        }
188

189
        internal static bool CreateRenameForm(ref string name, string tile = "")
190
        {
191
            ProcForm RenameFrm = new ProcForm(name);
192
            RenameFrm.groupBoxProcedure.Enabled = false;
193
            RenameFrm.Text = "Rename " + tile;
194
            RenameFrm.Create.Text = "OK";
195
            if (RenameFrm.ShowDialog() == DialogResult.Cancel || RenameFrm.ProcedureName.Length == 0) {
196
                return false;
197
            }
198
            name = RenameFrm.ProcedureName.Trim();
199
            RenameFrm.Dispose();
200
            return true;
201
        }
202

203
        private void tbName_Leave(object sender, EventArgs e)
204
        {
205
            if (isCreateProcedure && (!isSetName || tbName.Text.Length == 0)) {
206
                tbName.Text = "Example(arg0, arg1)";
207
                tbName.ForeColor = System.Drawing.Color.Gray;
208
                isSetName = false;
209
            }
210
        }
211

212
        private void tbName_Enter(object sender, EventArgs e)
213
        {
214
            if (!isSetName && tbName.Text.Length > 0) {
215
                tbName.ResetText();
216
                tbName.ForeColor = System.Drawing.SystemColors.ControlText;
217
            }
218
        }
219

220
        private void tbName_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
221
        {
222
            if (!isSetName) {
223
                tbName.ResetText();
224
                tbName.ForeColor = System.Drawing.SystemColors.ControlText;
225
                isSetName = true;
226
            }
227
        }
228

229
        private void tbName_MouseClick(object sender, MouseEventArgs e)
230
        {
231
            if (!isSetName) {
232
                tbName.ResetText();
233
                tbName.ForeColor = System.Drawing.SystemColors.ControlText;
234
                isSetName = true;
235
            }
236
        }
237
    }
238
}
239

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.