Skip to content

Commit fc537d3

Browse files
committed
Add code fixer for tab order
Handle scenarios without docking, e.g. all controls that have misaligned `TabIndex` vs z-order aren't docked. There are three distinct scenarios when it comes to re-ordering statements: 1. Move down by one, or swap neighbouring statements - in this case we need to swap the leading trivia before we switch. 2. Move down by more than one position - we need to swap leading trivia with the statement directly below the statement we are moving, and update the trivia for the moved statement with the leading trivia of the statement above which we're inserting. 3. Move up - we need to swap the leading trivia for the moved statement with the leading trivia of the statement above which we're inserting, and update that statement's trivia with the leading trivia of the statement directly below it.
1 parent 47d51ff commit fc537d3

13 files changed

+1231
-226
lines changed

src/WindowsForms.Analyzers/ControlTabOrderAnalyzer.cs

Lines changed: 77 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Collections.Generic;
55
using System.Collections.Immutable;
66
using System.Diagnostics;
7+
using System.Linq;
78
using Microsoft.CodeAnalysis;
89
using Microsoft.CodeAnalysis.CSharp.Syntax;
910
using Microsoft.CodeAnalysis.Diagnostics;
@@ -100,6 +101,49 @@ private void CodeBlockAction(OperationBlockAnalysisContext context)
100101
return;
101102
}
102103

104+
Dictionary<string, List<Location>> containerProperties = new();
105+
106+
// Check that 'container.Controls.Add(...)' statements are consequitive.
107+
// If not - the code has been manually modified, we won't be able to provide an auto-fix.
108+
foreach (string containerName in calculatedContext.ContainerAddLocations.Keys)
109+
{
110+
containerProperties[containerName] = new();
111+
112+
Location startLine = Location.None;
113+
Location endLine = Location.None;
114+
List<int> lines = new();
115+
foreach (Location location in calculatedContext.ContainerAddLocations[containerName])
116+
{
117+
if (startLine == Location.None || startLine.GetLineSpan().StartLinePosition.Line > location.GetLineSpan().StartLinePosition.Line)
118+
{
119+
startLine = location;
120+
}
121+
122+
if (endLine.GetLineSpan().StartLinePosition.Line < location.GetLineSpan().StartLinePosition.Line)
123+
{
124+
endLine = location;
125+
}
126+
127+
lines.Add(location.GetLineSpan().StartLinePosition.Line);
128+
}
129+
130+
Debug.Assert(startLine != Location.None);
131+
Debug.Assert(endLine != Location.None);
132+
133+
if (startLine == endLine)
134+
{
135+
// A single control with an invalid TabIndex
136+
}
137+
else if (Enumerable.Range(startLine.GetLineSpan().StartLinePosition.Line, endLine.GetLineSpan().StartLinePosition.Line - startLine.GetLineSpan().StartLinePosition.Line).Except(lines).Any())
138+
{
139+
// 'container.Controls.Add(...)' statements aren't consequitive.
140+
}
141+
else
142+
{
143+
containerProperties[containerName] = calculatedContext.ContainerAddLocations[containerName];
144+
}
145+
}
146+
103147
// _controlsAddIndex dictionary, which looks something like this:
104148
//
105149
// [this.Controls.Add] : new List { button3, this.button1 }
@@ -111,37 +155,46 @@ private void CodeBlockAction(OperationBlockAnalysisContext context)
111155
// [this.button1:1]
112156
// [label2:0]
113157
Dictionary<string, int> flatControlsAddIndex = new();
114-
foreach (string key in calculatedContext.ControlsAddIndex.Keys)
158+
Dictionary<string, string> containersByControl = new();
159+
foreach (string containerName in calculatedContext.ControlsAddIndex.Keys)
115160
{
116-
for (int i = 0; i < calculatedContext.ControlsAddIndex[key].Count; i++)
161+
for (int i = 0; i < calculatedContext.ControlsAddIndex[containerName].Count; i++)
117162
{
118-
string controlName = calculatedContext.ControlsAddIndex[key][i];
163+
string controlName = calculatedContext.ControlsAddIndex[containerName][i];
119164
flatControlsAddIndex[controlName] = i;
165+
166+
containersByControl[controlName] = containerName;
120167
}
121168
}
122169

123170
// Verify explicit TabIndex is the same as the "add order"
124-
foreach (string key in calculatedContext.ControlsTabIndex.Keys)
171+
foreach (string controlName in calculatedContext.ControlsTabIndex.Keys)
125172
{
126-
if (!flatControlsAddIndex.ContainsKey(key))
173+
if (!flatControlsAddIndex.ContainsKey(controlName))
127174
{
128175
// TODO: assert, diagnostics, etc.
129176
continue;
130177
}
131178

132-
int tabIndex = calculatedContext.ControlsTabIndex[key];
133-
int addIndex = flatControlsAddIndex[key];
179+
int tabIndex = calculatedContext.ControlsTabIndex[controlName];
180+
int addIndex = flatControlsAddIndex[controlName];
134181

135182
if (tabIndex == addIndex)
136183
{
137184
continue;
138185
}
139186

187+
string containerName = containersByControl[controlName];
188+
Dictionary<string, string?> properties = new();
189+
properties["ZOrder"] = addIndex.ToString();
190+
properties["TabIndex"] = tabIndex.ToString();
191+
140192
var diagnostic = Diagnostic.Create(
141193
descriptor: InconsistentTabIndexRuleIdDescriptor,
142-
location: calculatedContext.ControlsAddIndexLocations[key],
143-
properties: new Dictionary<string, string?> { { "ZOrder", addIndex.ToString() }, { "TabIndex", tabIndex.ToString() } }.ToImmutableDictionary(),
144-
key, addIndex, tabIndex);
194+
location: calculatedContext.ControlsAddIndexLocations[controlName],
195+
additionalLocations: containerProperties[containerName],
196+
properties.ToImmutableDictionary(),
197+
controlName, addIndex, tabIndex);
145198
context.ReportDiagnostic(diagnostic);
146199
}
147200
}
@@ -169,7 +222,7 @@ private void ParseControlAddStatements(InvocationExpressionSyntax expressionSynt
169222

170223
// this is something like "this.Controls.Add" or "panel1.Controls.Add", but good enough for our intents and purposes
171224
ExpressionSyntax? syntax = expressionSyntax.Expression;
172-
string container = syntax.ToString();
225+
string containerName = syntax.ToString();
173226

174227
// Transform "Controls.Add" statements into a map. E.g.:
175228
//
@@ -182,13 +235,20 @@ private void ParseControlAddStatements(InvocationExpressionSyntax expressionSynt
182235
// [this.Controls.Add] : new List { button3, this.button1 }
183236
// [panel1.Controls.Add] : new List { label2 }
184237

185-
if (!calculatedContext.ControlsAddIndex.ContainsKey(container))
238+
if (!calculatedContext.ControlsAddIndex.ContainsKey(containerName))
239+
{
240+
calculatedContext.ControlsAddIndex[containerName] = new List<string>();
241+
}
242+
243+
calculatedContext.ControlsAddIndex[containerName].Add(controlName);
244+
calculatedContext.ControlsAddIndexLocations[controlName] = syntax.Parent!.Parent!.GetLocation(); // e.g.: 'this.Controls.Add(button3);'
245+
246+
if (!calculatedContext.ContainerAddLocations.ContainsKey(containerName))
186247
{
187-
calculatedContext.ControlsAddIndex[container] = new List<string>();
248+
calculatedContext.ContainerAddLocations[containerName] = new();
188249
}
189250

190-
calculatedContext.ControlsAddIndex[container].Add(controlName);
191-
calculatedContext.ControlsAddIndexLocations[controlName] = syntax.Parent!.Parent!.GetLocation();
251+
calculatedContext.ContainerAddLocations[containerName].Add(calculatedContext.ControlsAddIndexLocations[controlName]);
192252
}
193253

194254
private void ParseTabIndexAssignments(AssignmentExpressionSyntax expressionSyntax, OperationBlockAnalysisContext context, CalculatedAnalysisContext calculatedContext)
@@ -246,6 +306,8 @@ private sealed class CalculatedAnalysisContext
246306
// Contains the list of fields and local controls in order those are added to parent controls.
247307
public Dictionary<string, List<string>> ControlsAddIndex { get; } = new();
248308
public Dictionary<string, Location> ControlsAddIndexLocations { get; } = new();
309+
310+
public Dictionary<string, List<Location>> ContainerAddLocations { get; } = new();
249311
}
250312
}
251313
}

src/WindowsForms.CodeFixes/CodeFixResources.Designer.cs

Lines changed: 25 additions & 36 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 5 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,6 @@
1-
<?xml version="1.0" encoding="utf-8"?>
1+
<?xml version="1.0" encoding="utf-8"?>
22
<root>
3-
<!--
4-
Microsoft ResX Schema
5-
6-
Version 2.0
7-
8-
The primary goals of this format is to allow a simple XML format
9-
that is mostly human readable. The generation and parsing of the
10-
various data types are done through the TypeConverter classes
11-
associated with the data types.
12-
13-
Example:
14-
15-
... ado.net/XML headers & schema ...
16-
<resheader name="resmimetype">text/microsoft-resx</resheader>
17-
<resheader name="version">2.0</resheader>
18-
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
19-
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
20-
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
21-
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
22-
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
23-
<value>[base64 mime encoded serialized .NET Framework object]</value>
24-
</data>
25-
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
26-
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
27-
<comment>This is a comment</comment>
28-
</data>
29-
30-
There are any number of "resheader" rows that contain simple
31-
name/value pairs.
32-
33-
Each data row contains a name, and value. The row also contains a
34-
type or mimetype. Type corresponds to a .NET class that support
35-
text/value conversion through the TypeConverter architecture.
36-
Classes that don't support this are serialized and stored with the
37-
mimetype set.
38-
39-
The mimetype is used for serialized objects, and tells the
40-
ResXResourceReader how to depersist the object. This is currently not
41-
extensible. For a given mimetype the value must be set accordingly:
42-
43-
Note - application/x-microsoft.net.object.binary.base64 is the format
44-
that the ResXResourceWriter will generate, however the reader can
45-
read any of the formats listed below.
46-
47-
mimetype: application/x-microsoft.net.object.binary.base64
48-
value : The object must be serialized with
49-
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
50-
: and then encoded with base64 encoding.
51-
52-
mimetype: application/x-microsoft.net.object.soap.base64
53-
value : The object must be serialized with
54-
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
55-
: and then encoded with base64 encoding.
563

57-
mimetype: application/x-microsoft.net.object.bytearray.base64
58-
value : The object must be serialized into a byte array
59-
: using a System.ComponentModel.TypeConverter
60-
: and then encoded with base64 encoding.
61-
-->
624
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
635
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
646
<xsd:element name="root" msdata:IsDataSet="true">
@@ -117,8 +59,8 @@
11759
<resheader name="writer">
11860
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
11961
</resheader>
120-
<data name="CodeFixTitle" xml:space="preserve">
121-
<value>Make uppercase</value>
122-
<comment>The title of the code fix.</comment>
62+
<data name="ControlTabOrderAnalyzerCodeFixTitle" xml:space="preserve">
63+
<value>Match Z-order to TabIndex</value>
64+
<comment>The title of the code fix. {Locked="TabIndex"}.</comment>
12365
</data>
124-
</root>
66+
</root>

0 commit comments

Comments
 (0)