Sfall-ScriptEditor

Форк
0
/
RegisterScript.cs 
384 строки · 14.7 Кб
1
using System;
2
using System.Collections.Generic;
3
using System.IO;
4
using System.Windows.Forms;
5
using System.Text;
6

7
using ScriptEditor.TextEditorUtilities;
8
using ICSharpCode.TextEditor.Util;
9

10
namespace ScriptEditor
11
{
12
    public partial class RegisterScript : Form
13
    {
14
        private static TextEditor TE;
15
        private Encoding lstEncoding;
16

17
        private class Entry
18
        {
19
            public int row;
20
            public string script;
21
            public string desc;
22
            public string name;
23
            public int vars;
24
            public string msglip;
25

26
            public Entry(int row, string line)
27
            {
28
                this.row = row;
29
                int descPos = line.IndexOf(';');
30
                int varPos  = line.LastIndexOf("# local_vars=");
31
                script = line.Remove(descPos).Trim();
32
                descPos++;
33
                desc = line.Substring(descPos, varPos - descPos).Trim();
34
                int.TryParse(line.Substring(varPos + 13), out vars);
35
            }
36

37
            public string GetAsString()
38
            {
39
                return script.PadRight(16) + "; " + desc.PadRight(45) + " # local_vars=" + vars.ToString();
40
            }
41

42
            public string GetMsgAsString()
43
            {
44
                if (name != null && Settings.EncCodePage.CodePage == 866)
45
                    name = name.Replace('\u0425', '\u0058'); //Replacement of Russian letter "X", to English letter
46
                return ("{" + (row + 101) + "}{" + msglip + "}{" + name + "}").PadRight(60) + "# " + script.PadRight(16) + "; " + desc;
47
            }
48
        }
49

50
        private struct cell
51
        {
52
            public int row;
53
            public int col;
54
        }
55

56
        cell SelectLine = new cell();
57

58
        private readonly List<string> lines;
59
        private readonly List<string> linesMsg;
60

61
        private readonly string lstPath;
62
        private readonly string msgPath;
63
        private readonly string headerPath;
64
        private bool cancel = false;
65
        private bool doAdd = false;
66
        private int scriptNumb = -1;
67
        private bool returnLine;
68
        private bool notSaved;
69

70
        private bool NotSaved
71
        {
72
            get { return notSaved; }
73
            set {
74
                Save_button.Text = "Saved";
75
                notSaved = value;
76
                if (value)
77
                    Save_button.Image = imageList1.Images[1];
78
                else
79
                    Save_button.Image = imageList1.Images[0];
80
            }
81
        }
82

83
        const string DESCMSG = "#\r\n#   This file was built using Sfall Script Editor.\r\n#";
84
        const string SCRIPT_H = "SCRIPT_";
85

86
        private void AddRow(Entry e)
87
        {
88
            dgvScripts.Rows.Add(e, e.row + 1, e.script, e.desc, e.vars, e.name);
89
            dgvScripts.Rows[dgvScripts.Rows.Count - 1].Cells[1].ToolTipText = "Unpack script from .dat";
90
        }
91

92
        private RegisterScript(string script, string lst, string msg, string header)
93
        {
94
            lstPath = lst;
95
            msgPath = msg;
96
            headerPath = header;
97
            InitializeComponent();
98

99
            dgvScripts.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
100
            char[] space = new char[] { ' ' };
101

102
            // определяем кодировку
103
            StreamReader fsr = FileReader.OpenStream(File.OpenRead(lst), Encoding.Default);
104
            lstEncoding = fsr.CurrentEncoding;
105
            fsr.Close();
106

107
            lines = new List<string>(File.ReadAllLines(lst, lstEncoding));
108

109
            if (script != null) {
110
                DefinetextBox.Text = SCRIPT_H + Path.GetFileNameWithoutExtension(script).ToUpper();
111
                for (int i = 0; i < lines.Count; i++)
112
                {
113
                    if (string.Compare(lines[i].Split(space, StringSplitOptions.RemoveEmptyEntries)[0], script, true) == 0) {
114
                        scriptNumb = i;
115
                        break;
116
                    }
117
                }   // new reg script
118
                if (scriptNumb == -1) {
119
                    scriptNumb = lines.Count;
120
                    lines.Add(script + "; # local_vars=0");
121
                    doAdd = true;
122
                    AllowCheckBox.Checked = Settings.allowDefine;
123
                    Save_button.Image = imageList1.Images[1];
124
                    notSaved = true;
125
                }
126
                AllowCheckBox.Enabled = true;
127
                DefinetextBox.Enabled = true;
128
            } else
129
                NotSaved = false;
130

131
            Entry[] entries = new Entry[lines.Count];
132
            for (int i = 0; i < lines.Count; i++)
133
                entries[i] = new Entry(i, lines[i]);
134
            lines.Clear();
135
            if (msgPath != null) {
136
                linesMsg = new List<string>(File.ReadAllLines(msg, Settings.EncCodePage));
137
                for (int i = 0; i < linesMsg.Count; i++)
138
                {
139
                    string[] line = linesMsg[i].Split('}');
140
                    if (line.Length != 4)
141
                        continue;
142
                    line[0] = line[0].TrimStart(' ', '{');
143
                    int lineno;
144
                    if (!int.TryParse(line[0], out lineno)) continue;
145
                    lineno -= 101;
146
                    if (lineno >= entries.Length) continue;
147
                    entries[lineno].name = line[2].TrimStart(' ', '{');
148
                    entries[lineno].msglip = line[1].TrimStart(' ', '{');
149
                }
150
                linesMsg.Clear();
151
            }
152
            for (int i = 0; i < entries.Length; i++)
153
            {
154
                AddRow(entries[i]);
155
            }
156
            if (scriptNumb != -1) {
157
                dgvScripts.FirstDisplayedScrollingRowIndex = (scriptNumb <= 5) ? scriptNumb : scriptNumb - 5;
158
                dgvScripts.Rows[scriptNumb].Selected = true;
159
            }
160
            dgvScripts.CellValueChanged += dgvScripts_CellValueChanged;
161
        }
162

163
        public static void Registration(string script)
164
        {
165
            if (Settings.outputDir == null) {
166
                MessageBox.Show("No output path selected.", "Error");
167
                return;
168
            }
169
            string lstPath = Path.Combine(Settings.outputDir, "scripts.lst");
170
            if (!File.Exists(lstPath)) {
171
                MessageBox.Show("scripts.lst does not exist in your scripts output directory", "Error");
172
                return;
173
            }
174
            string msgPath = Path.Combine(Settings.outputDir, "../text/english/game/scrname.msg");
175
            if (!File.Exists(msgPath)) {
176
                if (Settings.showWarnings) MessageBox.Show("Could not find file scrname.msg", "Warning");
177
                msgPath = null;
178
            }
179
            string scriptH = null;
180
            if (Settings.pathScriptsHFile == null) {
181
                if (Settings.showWarnings) MessageBox.Show("The path to scripts.h has not been set.", "Warning");
182
            } else {
183
                scriptH = Settings.pathScriptsHFile;
184
                if (!File.Exists(scriptH)) scriptH = null;
185
            }
186
            // Show form
187
            TE = (TextEditor)ActiveForm;
188
            TE.RegistredScriptDialogShow = true;
189
            (new RegisterScript(script, lstPath, msgPath, scriptH)).Show(ActiveForm);
190
        }
191

192
        private void RegisterScript_FormClosing(object sender, FormClosingEventArgs e)
193
        {
194
            if (cancel) return;
195
            if (NotSaved) {
196
                if (MessageBox.Show("Save all changed to files?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes) {
197
                    Save_button_Click(null, null);
198
                }
199
            }
200
            UndatFile.selectDatFile = null;
201
            TE.RegistredScriptDialogShow = false;
202
        }
203

204
        private void Save_button_Click(object sender, EventArgs e)
205
        {
206
            if (!NotSaved) return;
207
            dgvScripts.EndEdit();
208
            Entry[] entries = new Entry[dgvScripts.Rows.Count];
209
            for (int i = 0; i < entries.Length; i++)
210
            {
211
                int index = (int)dgvScripts.Rows[i].Cells[1].Value;
212
                entries[index - 1] = (Entry)dgvScripts.Rows[i].Cells[0].Value;
213
            }
214

215
            foreach (Entry entry in entries)
216
                lines.Add(entry.GetAsString());
217

218
            File.WriteAllLines(lstPath, lines.ToArray(), (FileReader.IsUnicode(lstEncoding)) ? new UTF8Encoding(false) : lstEncoding);
219
            lines.Clear();
220

221
            if (msgPath != null) {
222
                linesMsg.Add(DESCMSG);
223
                foreach (Entry entry in entries)
224
                    linesMsg.Add(entry.GetMsgAsString());
225

226
                File.WriteAllLines(msgPath, linesMsg.ToArray(), Settings.EncCodePage);
227
                linesMsg.Clear();
228
            }
229

230
            NotSaved = false;
231

232
            if (AllowCheckBox.Checked && headerPath == null) {
233
                MessageBox.Show("The definition was not added in header file.\nCould not find file scripts.h", "Script header error");
234
                return;
235
            }
236
            if (doAdd && AllowCheckBox.Checked) {
237
                Entry entry = entries[scriptNumb];
238
                List<string> hlines = new List<string>(File.ReadAllLines(headerPath));
239
                for (int j = hlines.Count - 1; j >= 0; j--)
240
                {
241
                    if (hlines[j].IndexOf('#') != -1 || j == 0) {
242
                        hlines.Insert(j, ("#define " + DefinetextBox.Text.ToUpperInvariant()).PadRight(32) + ("(" + (entry.row + 1) + ")").PadRight(8) + "// " + entry.script.PadRight(16) + "; " + entry.desc);
243
                        break;
244
                    }
245
                }
246
                File.WriteAllLines(headerPath, hlines.ToArray());
247
                doAdd = false;
248
            }
249
        }
250

251
        private void RegisterScript_KeyDown(object sender, KeyEventArgs e)
252
        {
253
            if (e.KeyCode == Keys.Escape) {
254
                cancel = true;
255
                e.Handled = true;
256
                Close();
257
            }
258
        }
259

260
        private void dgvScripts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
261
        {
262
            if (e.RowIndex == -1 || e.ColumnIndex == -1 || returnLine)
263
                return;
264
            DataGridViewCell cell = dgvScripts.Rows[e.RowIndex].Cells[e.ColumnIndex];
265
            Entry entry = (Entry)dgvScripts.Rows[e.RowIndex].Cells[0].Value;
266
            string val = (string)cell.Value;
267
            if (val == null) val = "";
268
            switch (e.ColumnIndex) {
269
                case 2:
270
                    if (Path.GetFileNameWithoutExtension(val).Length > 8) {
271
                        MessageBox.Show("Script file names must be 8 characters.", "Name Error");
272
                        returnLine = true;
273
                        cell.Value = entry.script;
274
                        break;
275
                    }
276
                    entry.script = val;
277
                    break;
278
                case 3:
279
                    entry.desc = val;
280
                    break;
281
                case 4:
282
                    int.TryParse(val, out entry.vars);
283
                    break;
284
                case 5:
285
                    if (val.IndexOfAny(new char[] { '{', '}' }) == -1)
286
                        entry.name = val;
287
                    break;
288
            }
289
            if (!returnLine) NotSaved = true;
290
            returnLine = false;
291
        }
292

293
        private cell Finds(int rowStart, int colStart, int rev = 1)
294
        {
295
            cell cell = new cell();
296
            string find_str = FindtextBox.Text.Trim();
297
            if (find_str.Length == 0) return cell;
298
            if (rev == -1 && rowStart == 0) rowStart = dgvScripts.RowCount - 1;
299
            for (int row = rowStart; row < dgvScripts.RowCount; row += rev)
300
            {
301
                if (row < 0) break;
302
                for (int col = colStart; col < dgvScripts.ColumnCount; col++)
303
                {
304
                    if (dgvScripts.Rows[row].Cells[col].Value == null)
305
                        continue;
306
                    string value = dgvScripts.Rows[row].Cells[col].Value.ToString();
307
                    if (value.IndexOf(find_str, 0, StringComparison.OrdinalIgnoreCase) != -1) {
308
                        cell.row = row;
309
                        cell.col = col;
310
                        break;
311
                    }
312
                }
313
                if (cell.col != 0) break;
314
                colStart = 1;
315
            }
316
            if (cell.col != 0) {
317
                dgvScripts.FirstDisplayedScrollingRowIndex = (cell.row <= 5) ? cell.row : cell.row - 5;
318
                dgvScripts.Rows[cell.row].Cells[cell.col].Selected = true;
319
            }
320
            return cell;
321
        }
322

323
        private void Addbutton_Click(object sender, EventArgs e)
324
        {
325
            dgvScripts.Sort(dgvScripts.Columns[1], System.ComponentModel.ListSortDirection.Ascending);
326
            Entry[] entries = new Entry[1];
327
            entries[0] = new Entry(dgvScripts.RowCount, "none.int; # local_vars=");
328
            AddRow(entries[0]);
329
            dgvScripts.FirstDisplayedScrollingRowIndex = dgvScripts.RowCount - 1;
330
            NotSaved = true;
331
        }
332

333
        private void Delbutton_Click(object sender, EventArgs e)
334
        {
335
            dgvScripts.Sort(dgvScripts.Columns[1], System.ComponentModel.ListSortDirection.Ascending);
336
            dgvScripts.Rows.RemoveAt(dgvScripts.RowCount - 1);
337
            dgvScripts.FirstDisplayedScrollingRowIndex = dgvScripts.RowCount - 1;
338
            NotSaved = true;
339
        }
340

341
        private void Downbutton_Click(object sender, EventArgs e)
342
        {
343
            cell curfind = Finds(SelectLine.row, SelectLine.col + 1);
344
            if (curfind.col == 0) MessageBox.Show("Nothing found.");
345
            else SelectLine = curfind;
346
        }
347

348
        private void Upbutton_Click(object sender, EventArgs e)
349
        {
350
            cell curfind = Finds(SelectLine.row, SelectLine.col + 1, -1);
351
            if (curfind.col == 0) MessageBox.Show("Nothing found.");
352
            else SelectLine = curfind;
353
        }
354

355
        private void dgvScripts_CellClick(object sender, DataGridViewCellEventArgs e)
356
        {
357
            SelectLine.col = e.ColumnIndex;
358
            SelectLine.row = e.RowIndex;
359
        }
360

361
        private void dgvScripts_CellContentClick(object sender, DataGridViewCellEventArgs e)
362
        {
363
            if (e.ColumnIndex == 1 && e.RowIndex > -1)
364
                OpenScript(dgvScripts.Rows[e.RowIndex].Cells[2].Value.ToString());
365
        }
366

367
        private void OpenScript(string scriptName)
368
        {
369
            if (Settings.outputDir == null)
370
                return;
371

372
            string pathScript = Path.Combine(Settings.outputDir, scriptName);
373
            if (!File.Exists(pathScript)) {
374
                var undat = new UndatFile();
375
                if (!undat.UnpackFile(ref pathScript)) {
376
                    if (pathScript != null)
377
                        MessageBox.Show("Unpack script file error.", "Open Script");
378
                    return;
379
                }
380
            }
381
            TE.Open(pathScript, TextEditor.OpenType.File, false, outputFolder : true);
382
        }
383
    }
384
}
385

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

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

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

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