-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAutoForm.cs
More file actions
589 lines (450 loc) · 22.3 KB
/
AutoForm.cs
File metadata and controls
589 lines (450 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
using gta5refactor.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gta5refactor
{
public partial class AutoForm : Form
{
MainForm OwnerForm;
volatile bool AbortOperation = false;
bool InProgress = false;
public AutoForm(MainForm owner)
{
InitializeComponent();
OwnerForm = owner;
FolderTextBox.Text = Settings.Default.ScriptFolder;
GlobalsFileNameTextBox.Text = Settings.Default.GlobalsFile;
}
private void FolderBrowseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog.SelectedPath = FolderTextBox.Text;
DialogResult res = FolderBrowserDialog.ShowDialog();
if (res == DialogResult.OK)
{
FolderTextBox.Text = FolderBrowserDialog.SelectedPath;
}
}
private void StartButton_Click(object sender, EventArgs e)
{
if (InProgress) return;
AutoRefactor2();
}
private void StopButton_Click(object sender, EventArgs e)
{
AbortOperation = true;
}
private void AutoRefactor()
{
AbortOperation = false;
InProgress = true;
string scriptfolder = FolderTextBox.Text;
string globalsfile = GlobalsFileNameTextBox.Text;
string functempl = FunctionTemplateComboBox.Text;
int threshold = (int)ThresholdUpDown.Value;
Task.Run(() =>
{
UpdateStatus("Task beginning...");
DateTime starttime = DateTime.Now;
string gfilepath = scriptfolder + "\\" + globalsfile;
ScriptFile.EnsureGlobalsFile(gfilepath);
int funcnumber = GetNextAvailableGlobalFunctionNumber(gfilepath, functempl, 1);
int errorcount = 0; //total number of errors encountered
int successcount = 0; //number of functions successfully refactored
List<string> errors = new List<string>();
int currentfuncline = 0;
Dictionary<string, ScriptFunction> ignorefuncs = new Dictionary<string, ScriptFunction>(); //funcs that were already matched to 2 or less copies
string[] scriptfiles = Directory.GetFiles(scriptfolder);
foreach (string scriptfile in scriptfiles)
{
if (AbortOperation)
{
UpdateStatus("AutoRefactor stopped at " + DateTime.Now.ToString() + ". Total duration: " + GetTimeStr(starttime));
AutoRefactorComplete();
return;
}
ignorefuncs.Clear();
ScriptFile file = new ScriptFile(scriptfile);
if (file.Name.ToLower() == globalsfile.ToLower()) continue; //don't autorefactor the globals file!
UpdateStatus(GetTimeStr(starttime) + ": AutoRefactoring " + scriptfile + "...");
file.Load();
ScriptFunction func = GetFirstRefactorableFunction(file, currentfuncline);
while (func != null)
{
string newname = string.Format(functempl, funcnumber);
string refacstrpart = file.Name + "::" + func.Name + " -> " + newname;
string refacstr = ": AutoRefactoring " + refacstrpart;
UpdateStatus(GetTimeStr(starttime) + refacstr + "...");
int cfile = 1;
//first step: find 100% function matches, this is basically the same as find matches function in MainForm
List<ScriptFunctionMatch> matches = new List<ScriptFunctionMatch>();
foreach (string matchfilep in scriptfiles)
{
if (AbortOperation)
{
UpdateStatus("AutoRefactor stopped at " + DateTime.Now.ToString() + ". Total duration: " + GetTimeStr(starttime));
AutoRefactorComplete();
return;
}
UpdateStatus(GetTimeStr(starttime) + refacstr + " : matching (" + cfile.ToString() + "/" + scriptfiles.Length.ToString() + ")...");
ScriptFile matchfile = new ScriptFile(matchfilep);
matchfile.Load();
foreach (ScriptFunction matchfunc in matchfile.Functions)
{
if (matchfunc.Length == func.Length)
{
ScriptFunctionMatch match = new ScriptFunctionMatch(matchfunc, func);
if (match.Match >= 100.0)
{
matches.Add(match);
}
}
}
matchfile.Unload(); //must save memory :(
cfile++;
}
//only autorefactor this if more matches than the threshold are found
if (matches.Count >= threshold)
{
UpdateStatus(GetTimeStr(starttime) + refacstr + " : Appending new globals function...");
file.AppendToGlobalsFile(func, newname, matches, gfilepath);
int cmatch = 1;
int initialerrcount = errorcount;
foreach (ScriptFunctionMatch match in matches)
{
if (AbortOperation)
{
//don't stop just now, wait until the current function is dealt with.
UpdateStatus("AutoRefactor stopping...");
}
else
{
UpdateStatus(GetTimeStr(starttime) + refacstr + " : refactoring (" + cmatch.ToString() + "/" + matches.Count.ToString() + ")...");
}
try
{
ScriptFile sfile = new ScriptFile(scriptfolder + "\\" + match.FileName);
sfile.Load();
if (sfile.RefactorFunction(match.Name, newname))
{
}
else
{
UpdateRefactorProgress("Error refactoring " + refacstrpart + ": " + sfile.LastError);
errors.Add(sfile.LastError);
errorcount++;
}
}
catch (Exception ex)
{
UpdateRefactorProgress("Error refactoring " + refacstrpart + ": " + ex.ToString());
errors.Add(ex.ToString());
errorcount++;
}
cmatch++;
}
if (initialerrcount == errorcount)
{
//no errors recorded here, count the success
successcount++;
int linecount = func.EndLine - func.StartLine;
UpdateRefactorProgress(refacstrpart + " (" + linecount.ToString() + " lines, " + matches.Count.ToString() + " matches)");
}
currentfuncline = 0; //start searching at the beginning of the file again since earlier funcs may now be refactorable!
//funcnumber++;
funcnumber = GetNextAvailableGlobalFunctionNumber(gfilepath, functempl, 1);
}
else
{
currentfuncline = func.EndLine;
if (!ignorefuncs.ContainsKey(func.Name))
{
ignorefuncs.Add(func.Name, func);
}
UpdateRefactorProgress("Skipped " + refacstrpart + " due to only " + matches.Count.ToString() + " matches.");
}
file = new ScriptFile(scriptfile);
file.Load();
func = GetFirstRefactorableFunction(file, currentfuncline);
while ((func != null) && ignorefuncs.ContainsKey(func.Name))
{
func = GetFirstRefactorableFunction(file, func.EndLine);
}
}
currentfuncline = 0; //reset search start for next file!
}
UpdateStatus("AutoRefactor completed at " + DateTime.Now.ToString() + ". Total duration: " + GetTimeStr(starttime));
AutoRefactorComplete();
});
}
private void AutoRefactor2()
{
AbortOperation = false;
InProgress = true;
string scriptfolder = FolderTextBox.Text;
string globalsfile = GlobalsFileNameTextBox.Text;
string functempl = FunctionTemplateComboBox.Text;
int threshold = Math.Max((int)ThresholdUpDown.Value, 1);
Task.Run(() =>
{
UpdateStatus("Task beginning...");
DateTime starttime = DateTime.Now;
string gfilepath = scriptfolder + "\\" + globalsfile;
string[] scriptfiles = Directory.GetFiles(scriptfolder);
string recursivefuncname = "XXXXXXXX__RECURSIVEFUNCTION__XXXXXXXX(";
int pass = 1;
while (true)
{
//stage 0: make sure the globals file is there
ScriptFile.EnsureGlobalsFile(gfilepath);
ScriptFile gfile = new ScriptFile(gfilepath);
gfile.Load();
//stage 1: find all currently refactorable functions in all files and smash them into a dictionary...
Dictionary<string, List<ScriptFunction>> foundfuncs = new Dictionary<string, List<ScriptFunction>>();
foreach (string scriptfile in scriptfiles)
{
if (AbortOperation)
{
UpdateStatus("AutoRefactor stopped at " + DateTime.Now.ToString() + ". Total duration: " + GetTimeStr(starttime));
AutoRefactorComplete();
return;
}
ScriptFile file = new ScriptFile(scriptfile);
if (file.Name.ToLower() == globalsfile) continue; //don't look in the globals file
UpdateStatus(GetTimeStr(starttime) + " : Searching " + file.Name + "...");
file.Load();
ScriptFunction func = null;
int currentline = 0;
//find all currently refactorable functions in this file, and add them to the dict
while ((func = GetFirstRefactorableFunction(file, currentline)) != null)
{
string funcstr = func.FunctionBody.Replace(func.Name + "(", recursivefuncname);
//uint funchash = JenkHash.GenHash(funcstr, JenkHashInputEncoding.UTF8);
List<ScriptFunction> hitlist = null;
if (!foundfuncs.TryGetValue(funcstr, out hitlist))
{
hitlist = new List<ScriptFunction>();
foundfuncs.Add(funcstr, hitlist);
}
hitlist.Add(func);
currentline = func.EndLine;
}
file.Unload();
}
GC.Collect(); //try keep the memory flowing
//stage 2: organise the found functions by the filename. allocate new global func names
Dictionary<string, List<ScriptFunction>> filefuncs = new Dictionary<string, List<ScriptFunction>>();
int curfuncnum = 1;
int foundfunccount = 0;
foreach (KeyValuePair<string, List<ScriptFunction>> kvp in foundfuncs)
{
if (kvp.Value.Count < threshold) continue; //skip this if below the threshold
foundfunccount++;
curfuncnum = GetNextAvailableGlobalFunctionNumber(gfile, functempl, curfuncnum);
string newname = string.Format(functempl, curfuncnum);
UpdateStatus(GetTimeStr(starttime) + " : Adding " + newname + " to " + gfile.Name + "...");
foreach (ScriptFunction func in kvp.Value)
{
List<ScriptFunction> flist;
if (!filefuncs.TryGetValue(func.File.Name, out flist))
{
flist = new List<ScriptFunction>();
filefuncs.Add(func.File.Name, flist);
}
func.NewName = newname;
flist.Add(func);
}
ScriptFunction usefunc = kvp.Value[0]; //use the first found func as the template for the globals.
string funcbody = kvp.Key.Replace(recursivefuncname, newname + "(");
//might be faster to use a stringbuilder to get the filewrite out of the loop..
usefunc.File.AppendToGlobalsFile(usefunc, newname, kvp.Value, gfilepath, funcbody);
string refacstrpart = "Added " + newname + " to " + gfile.Name;
int linecount = usefunc.EndLine - usefunc.StartLine;
UpdateRefactorProgress(refacstrpart + " (" + linecount.ToString() + " lines, " + kvp.Value.Count.ToString() + " matches)");
curfuncnum++;
}
foundfuncs.Clear();
//stage 3: go through all the files and refactor all found funcs in the file.
int grandtotfuncs = 0;
int grandtotlines = 0;
foreach (string scriptfile in scriptfiles)
{
ScriptFile file = new ScriptFile(scriptfile);
if (file.Name.ToLower() == globalsfile) continue; //don't refactor the globals file
List<ScriptFunction> ffuncs;
if (!filefuncs.TryGetValue(file.Name, out ffuncs)) continue; //no matches found for funcs in this file...
UpdateStatus(GetTimeStr(starttime) + " : Refactoring " + file.Name + "...");
file.Load();
file.RefactorFunctions(ffuncs);
file.Unload();
string refacstrpart = "Refactored " + ffuncs.Count.ToString() + " funcs in " + file.Name;
int totlines = 0;
foreach (ScriptFunction ffunc in ffuncs)
{
totlines += (ffunc.EndLine - ffunc.StartLine);
}
UpdateRefactorProgress(refacstrpart + " (" + totlines.ToString() + " total lines)");
grandtotfuncs += ffuncs.Count;
grandtotlines += totlines;
}
UpdateRefactorProgress("Pass " + pass.ToString() + " complete. " + grandtotfuncs.ToString() + " total functions refactored into "+foundfunccount+" global functions, " + grandtotlines + " total lines.");
pass++;
//try to keep the GC not confused...
foreach (KeyValuePair<string, List<ScriptFunction>> kvp in foundfuncs)
{
kvp.Value.Clear();
}
foreach (KeyValuePair<string, List<ScriptFunction>> kvp in filefuncs)
{
kvp.Value.Clear();
}
foundfuncs.Clear();
filefuncs.Clear();
GC.Collect(); //try keep the memory flowing
if (grandtotfuncs == 0)
{
break;
}
}
UpdateStatus("AutoRefactor completed at " + DateTime.Now.ToString() + ". Total duration: " + GetTimeStr(starttime));
UpdateRefactorProgress("AutoRefactor process complete.");
AutoRefactorComplete();
});
}
private void AutoRefactorComplete()
{
try
{
if (InvokeRequired)
{
Invoke(new Action(() => { AutoRefactorComplete(); }));
}
else
{
InProgress = false;
}
}
catch { }
}
private void UpdateRefactorProgress(string text)
{
try
{
if (InvokeRequired)
{
Invoke(new Action(() => { UpdateRefactorProgress(text); }));
}
else
{
LogTextBox.AppendText(text + "\r\n");
}
}
catch { }
}
private void UpdateStatus(string text)
{
try
{
if (InvokeRequired)
{
Invoke(new Action(() => { UpdateStatus(text); }));
}
else
{
StatusLabel.Text = text;
}
}
catch { }
}
private int GetNextAvailableGlobalFunctionNumber(string globalsfile, string functemplate, int start)
{
ScriptFile gf = new ScriptFile(globalsfile);
gf.Load();
return GetNextAvailableGlobalFunctionNumber(gf, functemplate, start);
}
private int GetNextAvailableGlobalFunctionNumber(ScriptFile gf, string functemplate, int start)
{
int num = start - 1;
string name;
bool found = true;
while (found)
{
num++;
name = string.Format(functemplate, num);
found = gf.FunctionMap.ContainsKey(name);
}
return num;
}
private ScriptFunction GetFirstRefactorableFunction(ScriptFile file, int startline)
{
string[] exclstarts = { "l_", "Local_", "iLocal_", "uLocal_", "fLocal_", "vLocal_", "sLocal_", "cLocal_" };
foreach (ScriptFunction func in file.Functions)
{
if (func.StartLine < startline) continue; //don't look at functions before the given line.
if (func.Name == "main") continue; //don't refactor main funcs...
//first test - does the function have no local dependencies?
bool haslocaldeps = false;
foreach (ScriptFunctionDependency funcdep in func.LocalDependencies)
{
if (funcdep.Name != func.Name)
{
haslocaldeps = true;
break;
}
}
if (haslocaldeps) continue;
//second test - does the function contain any references to local variables?
bool localfound = false;
for (int l = func.StartLine + 1; l <= func.EndLine; l++)
{
string line = file.FileLines[l];
int wordstart = 0;
bool inword = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if ((!inword) && (char.IsLetter(c) || (c=='_')))
{
inword = true;
wordstart = i;
}
else if (!(char.IsLetter(c) || char.IsNumber(c) || (c == '_')))
{
if (inword)
{
string word = line.Substring(wordstart, i - wordstart);
foreach (string exclstart in exclstarts)
{
if (word.StartsWith(exclstart))
{
localfound = true;
break;
}
}
if (localfound) break;
}
inword = false;
}
}
if (localfound) break;
}
if (!localfound)
{
return func;
}
}
return null;
}
private string GetTimeStr(DateTime starttime)
{
return (DateTime.Now - starttime).ToString("h\\:mm\\:ss");
}
}
}