forked from Vlad-Herus/CollapseRegionExtension
-
Notifications
You must be signed in to change notification settings - Fork 2
/
RegionCommands.cs
237 lines (206 loc) · 8.93 KB
/
RegionCommands.cs
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
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Outlining;
using Microsoft.VisualStudio.TextManager.Interop;
using Task = System.Threading.Tasks.Task;
namespace ToggleRegionsExtension
{
enum Operation
{
Expand,
Collapse,
Toggle,
Alternate
}
/// <summary>
/// Command handler
/// </summary>
internal sealed class RegionCommands
{
/// <summary>
/// Expand Command ID.
/// </summary>
public const int ExpandCommandId = 0x0100;
/// <summary>
/// Collapse Command ID.
/// </summary>
public const int CollapseCommandId = 0x0101;
/// <summary>
/// Toggle Command ID.
/// </summary>
public const int ToggleCommandId = 0x0102;
/// <summary>
/// Alternate Command ID.
/// </summary>
public const int AlternateCommandId = 0x0103;
/// <summary>
/// Command menu group (command set GUID).
/// </summary>
public static readonly Guid CommandSet = new Guid("e7b8c17f-d4e1-419b-a144-4cfec19ad1a4");
/// <summary>
/// VS Package that provides this command, not null.
/// </summary>
private readonly AsyncPackage _package;
/// <summary>
/// Initializes a new instance of the <see cref="RegionCommands"/> class.
/// Adds our command handlers for menu (commands must exist in the command table file)
/// </summary>
/// <param name="package">Owner package, not null.</param>
/// <param name="commandService">Command service to add command to, not null.</param>
private RegionCommands(AsyncPackage package, OleMenuCommandService commandService)
{
_package = package ?? throw new ArgumentNullException(nameof(package));
commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));
var expandCommandId = new CommandID(CommandSet, ExpandCommandId);
var expandMenuItem = new MenuCommand(Expand, expandCommandId);
commandService.AddCommand(expandMenuItem);
var collapseCommandId = new CommandID(CommandSet, CollapseCommandId);
var collapseMenuItem = new MenuCommand(Collapse, collapseCommandId);
commandService.AddCommand(collapseMenuItem);
var toggleCommandId = new CommandID(CommandSet, ToggleCommandId);
var toggleMenuItem = new MenuCommand(Toggle, toggleCommandId);
commandService.AddCommand(toggleMenuItem);
var alternateCommandId = new CommandID(CommandSet, AlternateCommandId);
var alternateMenuItem = new MenuCommand(Alternate, alternateCommandId);
commandService.AddCommand(alternateMenuItem);
}
/// <summary>
/// Gets the instance of the command.
/// </summary>
public static RegionCommands Instance
{
get;
private set;
}
/// <summary>
/// Gets the service provider from the owner package.
/// </summary>
private IAsyncServiceProvider ServiceProvider => _package;
/// <summary>
/// Initializes the singleton instance of the command.
/// </summary>
/// <param name="package">Owner package, not null.</param>
public static async Task InitializeAsync(AsyncPackage package)
{
// Switch to the main thread - the call to AddCommand in RegionCommands's constructor requires
// the UI thread.
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
var commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
Instance = new RegionCommands(package, commandService);
}
private void Expand(object sender, EventArgs e)
{
HandleOperation(Operation.Expand);
}
private void Collapse(object sender, EventArgs e)
{
HandleOperation(Operation.Collapse);
}
private void Toggle(object sender, EventArgs e)
{
HandleOperation(Operation.Toggle);
}
private void Alternate(object sender, EventArgs e)
{
HandleOperation(Operation.Alternate);
}
private void HandleOperation(Operation operation)
{
ThreadHelper.ThrowIfNotOnUIThread();
_ = _package.JoinableTaskFactory.RunAsync(async () =>
{
if (_package.DisposalToken.IsCancellationRequested)
{
return;
}
try
{
var (manager, regions) = await GetCurrentDocInfoAsync();
bool? shouldExpand = null;
if (operation == Operation.Expand)
{
shouldExpand = true;
}
if (operation == Operation.Collapse)
{
shouldExpand = false;
}
else if (operation == Operation.Alternate)
{
shouldExpand = regions.Any(region => region.IsCollapsed);
}
foreach (var region in regions)
{
if (shouldExpand != false && region is ICollapsed collapsed)
{
manager.Expand(collapsed);
}
else if (shouldExpand != true && !region.IsCollapsed)
{
manager.TryCollapse(region);
}
}
}
catch (Exception ex)
{
ActivityLog.LogError(ex.Source, ex.Message);
}
});
}
private async Task<(IOutliningManager manager, IEnumerable<ICollapsible> regions)> GetCurrentDocInfoAsync()
{
var emptyResult = (default(IOutliningManager), new ICollapsible[] { });
var textManager = await ServiceProvider.GetServiceAsync(typeof(SVsTextManager)) as IVsTextManager
?? throw new ApplicationException($"{nameof(SVsTextManager)} service is not available.");
var componentModel = await ServiceProvider.GetServiceAsync(typeof(SComponentModel)) as IComponentModel
?? throw new ApplicationException($"{nameof(SComponentModel)} service is not available.");
var outlining = componentModel.GetService<IOutliningManagerService>()
?? throw new ApplicationException($"{nameof(IOutliningManagerService)} service is not available.");
var editor = componentModel.GetService<IVsEditorAdaptersFactoryService>()
?? throw new ApplicationException($"{nameof(IVsEditorAdaptersFactoryService)} service is not available.");
textManager.GetActiveView(1, null, out IVsTextView textViewCurrent);
if (textViewCurrent == null)
{
return emptyResult;
}
var wpfView = editor.GetWpfTextView(textViewCurrent);
if (wpfView == null)
{
return emptyResult;
}
var outliningManager = outlining.GetOutliningManager(wpfView);
if (outliningManager == null)
{
return emptyResult;
}
List<ICollapsible> regions = new List<ICollapsible>();
var snapshot = new SnapshotSpan(wpfView.TextSnapshot, 0, wpfView.TextSnapshot.Length);
foreach (var region in outliningManager.GetAllRegions(snapshot))
{
var regionSnapshot = region.Extent.TextBuffer.CurrentSnapshot;
var text = region.Extent.GetText(regionSnapshot);
if (text.StartsWith("#region", StringComparison.CurrentCultureIgnoreCase) ||
text.StartsWith("#pragma region", StringComparison.CurrentCultureIgnoreCase))
{
regions.Add(region);
}
if (text.StartsWith("<!--"))
{
var textLow = text.ToLower();
if (textLow.Contains("region"))
{
regions.Add(region);
}
}
}
return (outliningManager, regions);
}
}
}