forked from pedropombeiro/ReSharper.AutoFormatOnSave
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReSharper.AutoFormatOnSavePackage.cs
462 lines (393 loc) · 16.2 KB
/
ReSharper.AutoFormatOnSavePackage.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
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
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReSharper.AutoFormatOnSavePackage.cs" company="Pedro Pombeiro">
// 2012 Pedro Pombeiro
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ReSharper.AutoFormatOnSave
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell.
/// </summary>
//// This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
// a package.
[PackageRegistration(UseManagedResourcesOnly = true)]
//// This attribute is used to register the informations needed to show the this package
//// in the Help/About dialog of Visual Studio.
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
[Guid(GuidList.guidReSharper_AutoFormatOnSavePkgString)]
[ProvideAutoLoad(UIContextGuids80.SolutionExists)]
public sealed class ReSharper_AutoFormatOnSavePackage : Package
{
#region Constants
/// <summary>
/// The name for the ReSharper silent code cleanup command.
/// </summary>
private const string ReSharperSilentCleanupCodeCommandName = "ReSharper_SilentCleanupCode";
#endregion
#region Static Fields
/// <summary>
/// The allowed file extensions for code cleanup.
/// </summary>
private static readonly string[] AllowedFileExtensions = new[] { ".cs", ".xaml", ".vb" };
#endregion
#region Fields
/// <summary>
/// The dictionary of documents which will be reformatted mapped to the timestamp when they were last reformatted.
/// </summary>
private readonly Dictionary<Document, DateTime> documentsToReformatDictionary = new Dictionary<Document, DateTime>();
/// <summary>
/// A timer which runs background checks (mainly to check whether all saves have completed).
/// </summary>
private readonly Timer timer = new System.Windows.Forms.Timer { Interval = 1000 };
/// <summary>
/// The Visual Studio build events object.
/// </summary>
private BuildEvents buildEvents;
/// <summary>
/// Positive value when the build engine is running.
/// </summary>
private int buildingSolution;
/// <summary>
/// The Visual Studio document events object.
/// </summary>
private DocumentEvents documentEvents;
/// <summary>
/// The DTE2 global service.
/// </summary>
private DTE2 dte;
/// <summary>
/// <c>true</c> if currently reformatting recently saved files.
/// </summary>
private bool isReformatting;
/// <summary>
/// The time of the last reformat.
/// </summary>
private DateTime lastReformat;
/// <summary>
/// The Visual Studio solution events object.
/// </summary>
private SolutionEvents solutionEvents;
/// <summary>
/// <c>true</c> if a solution is active.
/// </summary>
private bool solutionIsActive;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ReSharper_AutoFormatOnSavePackage"/> class.
/// Default constructor of the package.
/// Inside this method you can place any initialization code that does not require
/// any Visual Studio service because at this point the package object is created but
/// not sited yet inside Visual Studio environment. The place to do all the other
/// initialization is the Initialize method.
/// </summary>
public ReSharper_AutoFormatOnSavePackage()
{
Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this));
this.timer.Tick += this.TimerOnTick;
}
#endregion
#region Methods
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.DisconnectFromVsEvents();
this.timer.Tick -= this.TimerOnTick;
this.timer.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
protected override void Initialize()
{
Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this));
base.Initialize();
this.dte = (DTE2)GetGlobalService(typeof(DTE));
this.InitializeAddIn();
}
/// <summary>
/// Disconnect from <see cref="DocumentEvents"/>.
/// </summary>
private void DisconnectFromVsEvents()
{
if (this.documentEvents != null)
{
this.documentEvents.DocumentSaved -= this.OnDocumentSaved;
this.documentEvents.DocumentClosing -= this.OnDocumentClosing;
this.documentEvents = null;
}
if (this.buildEvents != null)
{
this.buildEvents.OnBuildBegin -= this.OnBuildBegin;
this.buildEvents.OnBuildDone -= this.OnBuildDone;
this.buildEvents = null;
}
if (this.solutionEvents != null)
{
this.solutionEvents.Opened -= this.OnOpenedSolution;
this.solutionEvents.BeforeClosing -= this.OnBeforeClosingSolution;
this.solutionEvents = null;
}
}
/// <summary>
/// Subscribes to the DocumentSaved event.
/// </summary>
private void InitializeAddIn()
{
if (this.dte.Commands.Cast<Command>().All(x => x.Name != ReSharperSilentCleanupCodeCommandName))
{
return;
}
var events2 = (EnvDTE80.Events2)this.dte.Events;
this.DisconnectFromVsEvents();
this.documentEvents = events2.DocumentEvents[null];
this.documentEvents.DocumentSaved += this.OnDocumentSaved;
this.documentEvents.DocumentClosing += this.OnDocumentClosing;
this.buildEvents = events2.BuildEvents;
this.buildEvents.OnBuildBegin += this.OnBuildBegin;
this.buildEvents.OnBuildDone += this.OnBuildDone;
this.solutionEvents = events2.SolutionEvents;
this.solutionEvents.Opened += this.OnOpenedSolution;
this.solutionEvents.BeforeClosing += this.OnBeforeClosingSolution;
this.timer.Start();
}
/// <summary>
/// The on before closing solution.
/// </summary>
private void OnBeforeClosingSolution()
{
this.solutionIsActive = false;
}
/// <summary>
/// Called when a build has begun.
/// </summary>
/// <param name="scope">
/// The build scope.
/// </param>
/// <param name="action">
/// The build action.
/// </param>
private void OnBuildBegin(vsBuildScope scope, vsBuildAction action)
{
switch (action)
{
case vsBuildAction.vsBuildActionBuild:
case vsBuildAction.vsBuildActionRebuildAll:
case vsBuildAction.vsBuildActionDeploy:
++this.buildingSolution;
break;
}
}
/// <summary>
/// Called when a build is done.
/// </summary>
/// <param name="scope">
/// The build scope.
/// </param>
/// <param name="action">
/// The build action.
/// </param>
private void OnBuildDone(vsBuildScope scope, vsBuildAction action)
{
switch (action)
{
case vsBuildAction.vsBuildActionBuild:
case vsBuildAction.vsBuildActionRebuildAll:
case vsBuildAction.vsBuildActionDeploy:
--this.buildingSolution;
break;
}
}
/// <summary>
/// Called when a document is being closed.
/// </summary>
/// <param name="document">
/// The document that is being closed.
/// </param>
private void OnDocumentClosing(Document document)
{
var extension = Path.GetExtension(document.FullName);
if (!AllowedFileExtensions.Contains(extension))
{
return;
}
// Do not reformat this document, because at this point, there is no longer a valid window to activate.
this.documentsToReformatDictionary.Remove(document);
}
/// <summary>
/// Called when a document is saved.
/// </summary>
/// <param name="document">
/// The document that was saved.
/// </param>
private void OnDocumentSaved(Document document)
{
if (this.isReformatting || this.buildingSolution > 0)
{
return;
}
var extension = Path.GetExtension(document.FullName);
if (AllowedFileExtensions.Contains(extension))
{
// Mark it for reformatting in our internal data structure
this.documentsToReformatDictionary[document] = DateTime.Now;
}
}
/// <summary>
/// Called when a solution is opened.
/// </summary>
private void OnOpenedSolution()
{
this.solutionIsActive = true;
}
/// <summary>
/// Reformats a given list of documents, ensuring that the background timer is stopped during the process.
/// </summary>
/// <param name="documentsToReformat">
/// The documents to reformat.
/// </param>
/// <param name="saveDocumentsAfterwards">
/// <c>true</c> if the changed documents should be saved afterwards.
/// </param>
private void ReformatDocuments(IEnumerable<Document> documentsToReformat, bool saveDocumentsAfterwards = false)
{
this.isReformatting = true;
this.timer.Stop();
this.lastReformat = DateTime.Now;
var originallyActiveWindow = this.dte.ActiveWindow;
try
{
var originallyActiveDocument = originallyActiveWindow != null
? originallyActiveWindow.Document
: null;
var activeDocumentCollection = originallyActiveDocument != null
? Enumerable.Repeat(originallyActiveDocument, 1)
: Enumerable.Empty<Document>();
// ReSharper disable PossibleMultipleEnumeration
var recentlySavedDocs =
documentsToReformat // .Where(x => x.ActiveWindow != null)
.Except(activeDocumentCollection)
.Concat(originallyActiveDocument != null && this.documentsToReformatDictionary.ContainsKey(originallyActiveDocument)
? activeDocumentCollection
: Enumerable.Empty<Document>())
// ReSharper restore PossibleMultipleEnumeration
.ToArray();
foreach (var document in recentlySavedDocs)
{
// Active the document which was just saved
document.Activate();
try
{
// so that we can run the ReSharper command on it.
this.dte.ExecuteCommand(ReSharperSilentCleanupCodeCommandName);
}
catch (Exception)
{
}
finally
{
this.documentsToReformatDictionary.Remove(document);
}
}
if (saveDocumentsAfterwards)
{
foreach (var document in recentlySavedDocs.Where(document => !document.Saved))
{
document.Save();
}
}
if (originallyActiveWindow != null)
{
// Reactivate the original window.
originallyActiveWindow.Activate();
}
}
finally
{
foreach (var document in documentsToReformat)
{
this.documentsToReformatDictionary.Remove(document);
}
this.timer.Start();
this.isReformatting = false;
}
}
/// <summary>
/// Called periodically.
/// </summary>
/// <param name="sender">
/// The timer.
/// </param>
/// <param name="eventArgs">
/// Nothing (<see cref="EventArgs.Empty"/>).
/// </param>
private void TimerOnTick(object sender, EventArgs eventArgs)
{
try
{
if (this.buildingSolution > 0)
{
this.documentsToReformatDictionary.Clear();
return;
}
// Sanity check
if (this.dte.Application.Mode == vsIDEMode.vsIDEModeDebug ||
this.isReformatting ||
!this.solutionIsActive ||
!this.documentsToReformatDictionary.Any())
{
return;
}
// Remove all unsaved documents from the dictionary
foreach (var document in this.documentsToReformatDictionary.Where(x => !x.Key.Saved).Select(x => x.Key).ToArray())
{
this.documentsToReformatDictionary.Remove(document);
}
var now = DateTime.Now;
if ((now - this.lastReformat).TotalSeconds < 5)
{
// Ignore any documents that have been saved if a reformat has happened within the last 5 seconds.
this.documentsToReformatDictionary.Clear();
return;
}
var anyDocumentSavedSinceLastCheck = this.documentsToReformatDictionary.Any(kvp => (now - kvp.Value).TotalMilliseconds < this.timer.Interval);
if (!this.documentsToReformatDictionary.Any() || anyDocumentSavedSinceLastCheck)
{
return;
}
this.ReformatDocuments(
this.documentsToReformatDictionary
.OrderBy(kvp => kvp.Value)
.Select(kvp => kvp.Key),
true);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(string.Format("{0}\n\n{1}", e.Message, e.StackTrace), "ReShaper.AutoFormatOnSave", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
}
}