-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathExtractLocalVariableCommand.cs
More file actions
272 lines (254 loc) · 11.3 KB
/
ExtractLocalVariableCommand.cs
File metadata and controls
272 lines (254 loc) · 11.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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ASCompletion.Completion;
using ASCompletion.Context;
using ASCompletion.Model;
using CodeRefactor.Provider;
using PluginCore;
using PluginCore.FRService;
using PluginCore.Helpers;
using PluginCore.Localization;
using PluginCore.Managers;
using ProjectManager.Helpers;
using ScintillaNet;
using ScintillaNet.Enums;
namespace CodeRefactor.Commands
{
internal class ExtractLocalVariableCommand : RefactorCommand<IDictionary<string, List<SearchMatch>>>
{
internal List<ICompletionListItem> CompletionList;
string newName;
/// <summary>
/// A new ExtractLocalVariableCommand refactoring command.
/// Outputs found results.
/// Uses the current selected text as the declaration target.
/// </summary>
public ExtractLocalVariableCommand() : this(true)
{
}
/// <summary>
/// A new ExtractLocalVariableCommand refactoring command.
/// Uses the current text as the declaration target.
/// </summary>
/// <param name="outputResults">If true, will send the found results to the trace log and results panel</param>
public ExtractLocalVariableCommand(bool outputResults) : this(outputResults, null)
{
}
/// <summary>
/// A new ExtractLocalVariableCommand refactoring command.
/// Uses the current text as the declaration target.
/// </summary>
/// <param name="outputResults">If true, will send the found results to the trace log and results panel</param>
/// <param name="newName">If provided, will not query the user for a new name.</param>
public ExtractLocalVariableCommand(bool outputResults, string newName)
{
OutputResults = outputResults;
this.newName = newName;
}
/// <summary>
/// Indicates if the current settings for the refactoring are valid.
/// </summary>
public override bool IsValid() => true;
/// <summary>
/// Entry point to execute renaming.
/// </summary>
protected override void ExecutionImplementation()
{
var sci = PluginBase.MainForm.CurrentDocument.SciControl;
var fileModel = ASContext.Context.GetCodeModel(ASContext.Context.CurrentModel, sci.Text);
var search = new FRSearch(sci.SelText) {SourceFile = sci.FileName};
var matches = search.Matches(sci.Text);
var currentMember = fileModel.Context.CurrentMember;
var lineFrom = currentMember.LineFrom;
var lineTo = currentMember.LineTo;
matches.RemoveAll(it => it.Line < lineFrom || it.Line > lineTo);
var target = matches.FindAll(it => sci.MBSafePosition(it.Index) == sci.SelectionStart);
if (matches.Count > 1)
{
CompletionList = new List<ICompletionListItem> {new CompletionListItem(target, sci, OnItemClick)};
CompletionList.Insert(0, new CompletionListItem(matches, sci, OnItemClick));
sci.DisableAllSciEvents = true;
PluginCore.Controls.CompletionList.Show(CompletionList, true);
}
else GenerateExtractVariable(target);
}
/// <summary>
/// This retrieves the new name from the user
/// </summary>
static string GetNewName()
{
var newName = "newVar";
var label = TextHelper.GetString("Label.NewName");
var title = TextHelper.GetString("Title.ExtractLocalVariableDialog");
using var dialog = new LineEntryDialog(title, label, newName);
var choice = dialog.ShowDialog();
var sci = PluginBase.MainForm.CurrentDocument.SciControl;
if (choice != DialogResult.OK)
{
sci.DisableAllSciEvents = false;
return null;
}
sci.DisableAllSciEvents = false;
var name = dialog.Line.Trim();
if (name.Length > 0 && name != newName) newName = name;
return newName;
}
void GenerateExtractVariable(List<SearchMatch> matches)
{
if (string.IsNullOrEmpty(newName)) newName = GetNewName();
if (string.IsNullOrEmpty(newName)) return;
var sci = PluginBase.MainForm.CurrentDocument?.SciControl;
if (sci is null) return;
var pos = sci.SelectionEnd;
var expr = ASComplete.GetExpressionType(sci, pos, false, true);
var type = !expr.IsNull() && expr.Type != null ? expr.Type.Name : string.Empty;
MemberModel import = null;
var ctx = ASContext.Context;
if (type != null && ctx.Settings.GenerateImports)
{
var model = expr.Type;
if (!string.IsNullOrEmpty(model?.InFile.Package) && !ctx.IsImported(model, sci.LineFromPosition(pos))) import = model;
}
sci.BeginUndoAction();
try
{
var expression = sci.SelText.Trim('=', ' ', '\t', '\n', '\r', ';', '.');
expression = expression.TrimEnd('(', '[', '{', '<');
expression = expression.TrimStart(')', ']', '}', '>');
var insertPosition = sci.PositionFromLine(ctx.CurrentMember.LineTo);
foreach (var match in matches)
{
var position = sci.MBSafePosition(match.Index);
insertPosition = Math.Min(insertPosition, position);
match.LineText = sci.GetLine(match.Line - 1);
}
insertPosition = sci.LineFromPosition(insertPosition);
insertPosition = sci.LineIndentPosition(insertPosition);
RefactoringHelper.ReplaceMatches(matches, sci, newName);
sci.SetSel(insertPosition, insertPosition);
var member = new MemberModel(newName, type, FlagType.LocalVar, 0) {Value = expression};
var snippet = TemplateUtils.GetTemplate("Variable");
snippet = TemplateUtils.ReplaceTemplateVariable(snippet, "Modifiers", null);
snippet = TemplateUtils.ToDeclarationString(member, snippet);
snippet += "$(Boundary)\n$(Boundary)";
SnippetHelper.InsertSnippetText(sci, sci.CurrentPos, snippet);
foreach (var match in matches)
{
match.Line += 1;
}
Results = new Dictionary<string, List<SearchMatch>> {{sci.FileName, matches}};
if (import != null) ASGenerator.GenerateJob(GeneratorJobType.AddImport, import, null, null, null);
if (OutputResults) ReportResults();
}
finally
{
sci.EndUndoAction();
}
}
/// <summary>
/// Outputs the results to the TraceManager
/// </summary>
void ReportResults()
{
var newNameLength = newName.Length;
PluginBase.MainForm.CallCommand("PluginCommand", "ResultsPanel.ClearResults;" + PluginMain.TraceGroup);
foreach (var entry in Results)
{
var lineOffsets = new Dictionary<int, int>();
var lineChanges = new Dictionary<int, string>();
var reportableLines = new Dictionary<int, List<string>>();
foreach (var match in entry.Value)
{
var column = match.Column;
var lineNumber = match.Line;
var changedLine = lineChanges.ContainsKey(lineNumber) ? lineChanges[lineNumber] : match.LineText;
var offset = lineOffsets.ContainsKey(lineNumber) ? lineOffsets[lineNumber] : 0;
column += offset;
changedLine = changedLine.Substring(0, column) + newName + changedLine.Substring(column + match.Length);
lineChanges[lineNumber] = changedLine;
lineOffsets[lineNumber] = offset + (newNameLength - match.Length);
if (!reportableLines.ContainsKey(lineNumber)) reportableLines[lineNumber] = new List<string>();
reportableLines[lineNumber].Add(entry.Key + ":" + match.Line + ": chars " + column + "-" + (column + newNameLength) + " : {0}");
}
foreach (var lineSetsToReport in reportableLines)
{
var renamedLine = lineChanges[lineSetsToReport.Key].Trim();
foreach (var lineToReport in lineSetsToReport.Value)
{
TraceManager.Add(string.Format(lineToReport, renamedLine), (int) TraceType.Info, PluginMain.TraceGroup);
}
}
}
PluginBase.MainForm.CallCommand("PluginCommand", "ResultsPanel.ShowResults;" + PluginMain.TraceGroup);
}
void OnItemClick(object sender, EventArgs e) => GenerateExtractVariable(((CompletionListItem) sender).Matches);
}
internal sealed class CompletionListItem : ToolStripMenuItem, ICompletionListItem
{
const int Indicator = 0;
public readonly List<SearchMatch> Matches;
public readonly ScintillaControl Sci;
public CompletionListItem(List<SearchMatch> matches, ScintillaControl sci, EventHandler onClick)
{
var count = matches.Count;
Text = string.Format(TextHelper.GetString("Info.ReplacedOccurrences"), count);
description = count == 1
? TextHelper.GetString("Description.ReplaceInitialOccurrence")
: TextHelper.GetString("Description.ReplaceAllOccurrences");
Click += onClick;
Icon = new Bitmap(16, 16);
Matches = matches;
Sci = sci;
}
public string Label => Text;
public string Value
{
get
{
RemoveHighlights();
PerformClick();
return null;
}
}
readonly string description;
public string Description
{
get
{
RemoveHighlights();
if (Matches != null)
{
foreach (var m in Matches)
{
Highlight(m.Index, m.Length);
}
}
return description;
}
}
public Bitmap Icon { get; }
/// <summary>
/// Modify the highlight indicator alpha and select current word.
/// </summary>
void RemoveHighlights()
{
Sci.RemoveHighlights(Indicator);
Sci.SetIndicSetAlpha(Indicator, 100);
}
/// <summary>
/// Highlight the specified region.
/// </summary>
/// <param name="startIndex">The start index of the highlight.</param>
/// <param name="length">The length of the highlight.</param>
void Highlight(int startIndex, int length)
{
Sci.SetIndicStyle(Indicator, (int) IndicatorStyle.Container);
Sci.SetIndicFore(Indicator, 0x00FF00);
Sci.CurrentIndicator = Indicator;
Sci.IndicatorFillRange(startIndex, length);
Sci.StartStyling(Sci.EndStyled, 0xff);
}
}
}