From 0fc040f9d025034d264057423c3f0b215eb2d508 Mon Sep 17 00:00:00 2001 From: Fabrice Foray Date: Tue, 17 Nov 2026 23:57:20 +0100 Subject: [PATCH] [VSIntegration] ShadowDesigner: solve the "save solution?" prompt that might leave a stale companion. Move the caret inside a new event handler After using the designer, closing the solution always asked to save it, and answering No made VS 2026 report the companion project as not found on the next open. --- .../ShadowDesigner/CompanionSaveWatcher.cs | 174 +++++++++++-- .../ShadowDesigner/ShadowDesignerCleanup.cs | 123 +++------- .../ShadowDesigner/SolutionFileCleanup.cs | 228 ++++++++++++++++++ .../ShadowDesigner/SolutionWiring.cs | 46 ++++ 4 files changed, 458 insertions(+), 113 deletions(-) create mode 100644 src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionFileCleanup.cs diff --git a/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/CompanionSaveWatcher.cs b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/CompanionSaveWatcher.cs index da5d22a6a9..af068eecc2 100644 --- a/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/CompanionSaveWatcher.cs +++ b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/CompanionSaveWatcher.cs @@ -39,9 +39,9 @@ namespace XSharp.ProjectSystem.ShadowDesigner /// /// "On save" specifically (via IVsRunningDocTableEvents.OnAfterSave), not an idle timer /// or tab-switch hook: both sync commands read the companion files from disk, not the - /// live editor buffer -- the same reason the manual commands force-run File.SaveAll - /// first. So on-save is the earliest moment the data is actually available, not an - /// arbitrary cadence choice. + /// live editor buffer, which is also why the other companion documents are saved first + /// (SaveCompanionDocuments). So on-save is the earliest moment the data is actually + /// available, not an arbitrary cadence choice. /// /// Also intercepts the Designer navigating to the companion file's CODE view /// (event-handler creation/navigation) via OnBeforeDocumentWindowShow, and redirects to @@ -144,11 +144,6 @@ public int OnAfterSave(uint docCookie) string path = GetDocumentMoniker(docCookie); if (string.IsNullOrEmpty(path)) { - // Not Form1.cs/Form1.Designer.cs -- still worth checking whether this is a - // .resx living directly in a known companion folder (e.g. a new - // Form1.nl.resx from changing the form's Language property), since that can - // be saved without either code file ever becoming dirty. - TryHandleResxOnlySave(path); return VSConstants.S_OK; } @@ -168,9 +163,8 @@ public int OnAfterSave(uint docCookie) // The save that triggered this event only guarantees ONE of the two // companion files is current on disk -- the other may still be dirty in a // different editor tab (e.g. a new handler stub in Form1.cs while only - // Form1.Designer.cs was just saved). Force both current first, same safety - // net the manual sync commands already use. - SaveDirtyDocuments(); + // Form1.Designer.cs was just saved). Force both current first. + SaveCompanionDocuments(location); EventHandlerSync.Sync(location); DesignerChangesSync.Sync(location); CompanionResourceSync.Sync(location); @@ -231,6 +225,11 @@ private void TryHandleResxOnlySave(string path) } } static bool saving = false; + /// + /// Saves every dirty document, before Debug/Start only (VS saves them for the build anyway). Not used by the + /// syncs: called from OnAfterSave, saving the solution as well failed with a recursive save error, see + /// SaveCompanionDocuments. + /// private void SaveDirtyDocuments() { ThreadHelper.ThrowIfNotOnUIThread(); @@ -238,15 +237,63 @@ private void SaveDirtyDocuments() if (! saving) { saving = true; - int hr = _rdt.SaveDocuments((uint)__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty, - null, VSConstants.VSITEMID_NIL, VSConstants.VSCOOKIE_NIL); - ErrorHandler.ThrowOnFailure(hr); - if (hr != VSConstants.S_OK) + try { - throw new InvalidOperationException("Saving documents was cancelled; shadow designer synchronization was not performed."); + int hr = _rdt.SaveDocuments((uint)__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty, + null, VSConstants.VSITEMID_NIL, VSConstants.VSCOOKIE_NIL); + ErrorHandler.ThrowOnFailure(hr); + if (hr != VSConstants.S_OK) + { + throw new InvalidOperationException("Saving documents was cancelled; shadow designer synchronization was not performed."); + } } - saving = false; + finally + { + // Also after a failed or cancelled save, otherwise nothing is saved anymore + saving = false; + } + } + } + /// + /// Saves the companion's own documents that are still dirty (the other code file, a resx), since the syncs + /// read them from disk. Deliberately not all documents (File.SaveAll, SaveDirtyDocuments): that also saved + /// the user's other documents and unsaved solution changes (which is how the companion ended up in the saved + /// solution file), and saving the solution from inside OnAfterSave failed with "A recursive save operation + /// is in progress for '....slnx'" (VS 2026, after adding a Solution Folder). + /// + private void SaveCompanionDocuments(CompanionLocation location) + { + ThreadHelper.ThrowIfNotOnUIThread(); + string companionDir = Path.GetDirectoryName(location.CompanionDesignerCsPath); + if (string.IsNullOrEmpty(companionDir) || + ErrorHandler.Failed(_rdt.GetRunningDocumentsEnum(out IEnumRunningDocuments documents)) || documents == null) + { + return; + } + // Collected first: saving while enumerating could change the table + var toSave = new List(); + var cookies = new uint[1]; + while (documents.Next(1, cookies, out uint fetched) == VSConstants.S_OK && fetched == 1) + { + string path = GetDocumentMoniker(cookies[0]); + if (path != null && + string.Equals(Path.GetDirectoryName(path), companionDir, StringComparison.OrdinalIgnoreCase) && + (path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".resx", StringComparison.OrdinalIgnoreCase))) + { + toSave.Add(cookies[0]); + } + } + foreach (uint cookie in toSave) + { + if (ErrorHandler.Succeeded(_rdt.GetDocumentInfo(cookie, out _, out _, out _, out string path, out IVsHierarchy hierarchy, out uint itemId, out _))) + { + int hr = _rdt.SaveDocuments((uint)__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty, hierarchy, itemId, cookie); + if (ErrorHandler.Failed(hr)) + { + Logger.Information($"CompanionSaveWatcher: could not save {path}, hr=0x{hr:X8}"); + } + } } } @@ -295,7 +342,7 @@ public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowF // Same reasoning as OnAfterSave: the sync command reads from disk, and the // Designer's own navigation flow may have flushed its pending edits into the // companion buffer without that being on disk yet. - SaveDirtyDocuments(); + SaveCompanionDocuments(location); result = EventHandlerSync.Sync(location); CompanionResourceSync.Sync(location); } @@ -407,6 +454,7 @@ private async Task RedirectNowAsync(CompanionLocation location, IVsWindowFrame c Logger.Exception(ex, "CompanionSaveWatcher.RedirectNowAsync: CloseFrame failed"); } + ReloadOpenDocument(location.MainPrgPath); VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, location.MainPrgPath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out IVsWindowFrame frame); @@ -479,14 +527,19 @@ private static string TryGetCaretMethodName(IVsWindowFrame companionFrame, strin /// /// The returned frame's text view may still be initializing; poll that frame briefly /// rather than navigating whichever document happens to be active. + /// + /// The declaration is searched in the editor buffer, not in the file: a new stub is + /// written to disk by EventHandlerSync, and a .prg that is already open is only + /// reloaded by VS a moment later. A line number taken from the file then pointed past + /// the end of the old, shorter buffer (caret at the end of the file, while a second + /// try worked). RedirectNowAsync therefore reloads the document first + /// (ReloadOpenDocument); the buffer is still polled briefly in case that was skipped. /// private async Task NavigateToMethodAsync(IVsWindowFrame frame, string prgPath, string handlerName) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - string[] lines = File.ReadAllLines(prgPath); var pattern = new Regex($@"\bMETHOD\s+{Regex.Escape(handlerName)}\s*\(", RegexOptions.IgnoreCase); - int declLineIndex = Array.FindIndex(lines, l => pattern.IsMatch(l)); - if (declLineIndex < 0) + if (!File.ReadLines(prgPath).Any(l => pattern.IsMatch(l))) { return false; } @@ -508,9 +561,32 @@ private async Task NavigateToMethodAsync(IVsWindowFrame frame, string prgP return false; } - int targetLine = (declLineIndex + 1 < lines.Length) ? declLineIndex + 1 : declLineIndex; ErrorHandler.ThrowOnFailure(textView.GetBuffer(out IVsTextLines buffer)); - ErrorHandler.ThrowOnFailure(buffer.GetLineCount(out int lineCount)); + int declLineIndex = -1; + int lineCount = 0; + const int maxAttempts = 40; + for (int attempt = 0; attempt < maxAttempts; attempt++) + { + ErrorHandler.ThrowOnFailure(buffer.GetLineCount(out lineCount)); + declLineIndex = FindLine(buffer, lineCount, pattern); + if (declLineIndex >= 0) + { + if (attempt > 0) + { + Logger.Information($"CompanionSaveWatcher.NavigateToMethodAsync: waited {attempt * 50} ms for {prgPath} to be reloaded"); + } + break; + } + await Task.Delay(50); + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + } + if (declLineIndex < 0) + { + Logger.Error($"CompanionSaveWatcher.NavigateToMethodAsync: '{handlerName}' not found in the editor buffer of {prgPath} after {maxAttempts * 50} ms."); + return false; + } + + int targetLine = (declLineIndex + 1 < lineCount) ? declLineIndex + 1 : declLineIndex; int endLine = targetLine; int endColumn; if (targetLine + 1 < lineCount) @@ -533,6 +609,58 @@ private async Task NavigateToMethodAsync(IVsWindowFrame frame, string prgP return true; } + /// + /// Reloads from disk when it is open in an editor without unsaved changes. EventHandlerSync + /// writes new handler stubs to the file; VS reloads an open document only when the UI thread is idle, which + /// never happens while the new-handler redirect runs (JoinableTaskFactory.Run in OnBeforeDocumentWindowShow), + /// so NavigateToMethodAsync would search a buffer without the new stub. A document with unsaved changes is + /// left alone: reloading would lose them. + /// + private void ReloadOpenDocument(string path) + { + ThreadHelper.ThrowIfNotOnUIThread(); + if (ErrorHandler.Failed(_rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, path, + out _, out _, out IntPtr docDataPtr, out _)) || docDataPtr == IntPtr.Zero) + { + return; + } + try + { + if (System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(docDataPtr) is IVsPersistDocData docData && + ErrorHandler.Succeeded(docData.IsDocDataDirty(out int dirty)) && dirty == 0) + { + // The file change notification of the sync's own write would reload it a second time + int hr = docData.ReloadDocData((uint)_VSRELOADDOCDATA.RDD_IgnoreNextFileChange); + Logger.Information($"CompanionSaveWatcher.ReloadOpenDocument: reloaded {path}, hr=0x{hr:X8}"); + } + } + catch (Exception ex) + { + // Best-effort: NavigateToMethodAsync still polls the buffer + Logger.Exception(ex, $"CompanionSaveWatcher.ReloadOpenDocument: could not reload {path}"); + } + finally + { + System.Runtime.InteropServices.Marshal.Release(docDataPtr); + } + } + + /// The 0-based index of the first buffer line matching , or -1. + private static int FindLine(IVsTextLines buffer, int lineCount, Regex pattern) + { + ThreadHelper.ThrowIfNotOnUIThread(); + for (int line = 0; line < lineCount; line++) + { + if (ErrorHandler.Succeeded(buffer.GetLengthOfLine(line, out int length)) && + ErrorHandler.Succeeded(buffer.GetLineText(line, 0, line, length, out string text)) && + pattern.IsMatch(text)) + { + return line; + } + } + return -1; + } + public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) => VSConstants.S_OK; } } diff --git a/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/ShadowDesignerCleanup.cs b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/ShadowDesignerCleanup.cs index 4c05e71359..3d06588d62 100644 --- a/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/ShadowDesignerCleanup.cs +++ b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/ShadowDesignerCleanup.cs @@ -11,15 +11,10 @@ using System.Collections.Generic; using System.IO; using System.Threading; -using System.Xml; - using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; -using Community.VisualStudio.Toolkit; - - namespace XSharp.ProjectSystem.ShadowDesigner { /// @@ -48,6 +43,12 @@ namespace XSharp.ProjectSystem.ShadowDesigner /// prompt). The companion projects are then no longer in the solution, which is harmless: their paths stay /// tracked, the next View Designer adds the project back (SolutionWiring.EnsureProjectInSolution), and the /// folders are only deleted after a real close. + /// + /// Removing the companion makes the solution dirty. When nothing else was unsaved it is saved right away, so + /// VS does not ask to save the solution because of the companion. When VS does ask (other unsaved changes) and + /// the user answers No, the solution file can still list the companion (saved when it was added, or by a Save + /// All): OnAfterCloseSolution removes it from the file (SolutionFileCleanup), since VS 2026 reports a project + /// that is not found with an error on the next open. /// internal sealed class ShadowDesignerCleanup : IVsSolutionEvents { @@ -68,6 +69,9 @@ internal sealed class ShadowDesignerCleanup : IVsSolutionEvents private readonly IVsSolution _vsSolution; private uint _eventsCookie; + // The file of the closing solution (OnQueryCloseSolution), cleaned in OnAfterCloseSolution + private string _closingSolutionFile; + private ShadowDesignerCleanup(IServiceProvider serviceProvider) { ThreadHelper.ThrowIfNotOnUIThread(); @@ -78,87 +82,8 @@ private ShadowDesignerCleanup(IServiceProvider serviceProvider) } _vsSolution = (IVsSolution)solutionService; ErrorHandler.ThrowOnFailure(_vsSolution.AdviseSolutionEvents(this, out _eventsCookie)); - // Trigger cleanup before solution is closed - VS.Commands.InterceptAsync(VSConstants.VSStd97CmdID.CloseSolution, () => - { - ThreadHelper.ThrowIfNotOnUIThread(); - CleanupAndSave(); - return CommandProgression.Continue; - }).FileAndForget("XSharp/ShadowDesigner/CloseSolution"); - VS.Events.SolutionEvents.OnBeforeCloseSolution += SolutionEvents_OnBeforeCloseSolution; - VS.Events.SolutionEvents.OnAfterCloseSolution += SolutionEvents_OnAfterCloseSolution; } - string solutionName = ""; - private void SolutionEvents_OnBeforeCloseSolution() - { - solutionName = VS.Solutions.GetCurrentSolution().FullPath; - } - - private void SolutionEvents_OnAfterCloseSolution() - { - const string folderName = "Shadow Designer (generated)"; - if (File.Exists(solutionName)) - { - var files = new List(); - foreach (var file in _companionCsprojPaths) - { - files.Add(System.IO.Path.GetFileName(file)); - } - - var text = File.ReadAllText(solutionName); - // Slnx? - if (text.StartsWith("<")) - { - var reader = new StreamReader(solutionName); - var doc = new System.Xml.XmlDocument(); - doc.Load(reader); - reader.Close(); - XmlNode root = doc.DocumentElement; - var nodes = root.SelectNodes("Folder"); - foreach (XmlNode node in nodes) - { - if (node.OuterXml.Contains(folderName)) - { - root.RemoveChild(node); - } - } - doc.Save(solutionName); - return; - - } - // Sln - var lines = File.ReadAllLines(solutionName); - - for (int i = 0; i < lines.Length; i++) - { - var line = lines[i]; - foreach (var file in files) - { - if (line.IndexOf(file, StringComparison.OrdinalIgnoreCase) >= 0) - { - lines[i] = ""; - lines[i + 1] = ""; - } - } - if (line.IndexOf(folderName, StringComparison.OrdinalIgnoreCase) >= 0) - { - lines[i] = ""; - lines[i + 1] = ""; - } - } - File.WriteAllLines(solutionName, lines); - } - solutionName = ""; - } - - private void CleanupAndSave() - { - CleanupSolution(); - VS.Commands.ExecuteAsync(VSConstants.VSStd97CmdID.SaveSolution).FileAndForget("XSharp/ShadowDesigner/SaveSolution"); - } - - /// /// Registers a companion project for cleanup on solution close, lazily advising /// solution events the first time this is called. Safe to call every time @@ -201,10 +126,23 @@ public static void CancelPendingDelete(string companionDir) } } - private void CleanupSolution() + /// + /// Runs for every close (Close Solution, exiting VS, opening another solution), before VS's save prompt. + /// + public int OnQueryCloseSolution(object reserved, ref int cancel) { - if (_vsSolution != null) + // Another listener already cancelled the close: the solution stays open, keep the companions. + if (cancel != 0) { + return VSConstants.S_OK; + } + if (_vsSolution != null && _companionCsprojPaths.Count > 0) + { + _closingSolutionFile = SolutionWiring.GetSolutionFile(_vsSolution); + // Nothing else unsaved: the removal below is the only change, save it without asking (see + // SolutionWiring.EnsureProjectInSolution). Otherwise VS asks as usual; when the user answers No, + // OnAfterCloseSolution removes the companion from the solution file. + bool wasDirty = SolutionWiring.IsSolutionDirty(_vsSolution); foreach (string csprojPath in _companionCsprojPaths) { try @@ -234,11 +172,11 @@ private void CleanupSolution() // Best-effort, see above Logger.Exception(ex, "ShadowDesignerCleanup: could not remove the Solution Folder"); } + if (!wasDirty) + { + SolutionWiring.SaveSolutionFile(_vsSolution, "companion removed"); + } } - } - - public int OnQueryCloseSolution(object reserved, ref int cancel) - { return VSConstants.S_OK; } @@ -376,6 +314,11 @@ public int OnAfterCloseSolution(object reserved) // that could take, retry on a background thread instead -- costs nothing (this is // best-effort cleanup either way) and gives the external process realistic time to // release its handle. + // Answering No to VS's save prompt keeps the companion in the solution file when it was saved earlier + // (EnsureProjectInSolution, or a Save All). The folder is deleted below, so VS would report the project + // as not found on the next open: remove it from the file too. + SolutionFileCleanup.RemoveCompanionProjects(_closingSolutionFile, _companionCsprojPaths); + _closingSolutionFile = null; foreach (string csprojPath in _companionCsprojPaths) { string dir = Path.GetDirectoryName(csprojPath); diff --git a/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionFileCleanup.cs b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionFileCleanup.cs new file mode 100644 index 0000000000..adafd616ee --- /dev/null +++ b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionFileCleanup.cs @@ -0,0 +1,228 @@ +// +// Copyright (c) XSharp B.V. All Rights Reserved. +// Licensed under the Apache License, Version 2.0. +// See License.txt in the project root for license information. +// +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Linq; + +namespace XSharp.ProjectSystem.ShadowDesigner +{ + /// + /// Removes the companion projects, and the "Shadow Designer (generated)" Solution Folder once it is empty, from a + /// solution file (.slnx or .sln) after VS closed the solution. Only needed when the user answered No to VS's + /// save prompt while the file still listed a companion (see ShadowDesignerCleanup). Only these entries are + /// removed; the rest of the file, its encoding and its line endings are kept. Pure file I/O, no VS API. + /// + internal static class SolutionFileCleanup + { + private const string SolutionFolderTypeGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"; + + public static void RemoveCompanionProjects(string solutionFile, ICollection companionCsprojPaths) + { + if (string.IsNullOrEmpty(solutionFile) || companionCsprojPaths == null || companionCsprojPaths.Count == 0 || + !File.Exists(solutionFile)) + { + return; + } + try + { + byte[] bytes = File.ReadAllBytes(solutionFile); + bool bom = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; + if (!bom && bytes.Length >= 2 && (bytes[0] == 0xFF || bytes[0] == 0xFE)) + { + // UTF-16: not written by VS for .sln/.slnx, left alone + return; + } + var encoding = new UTF8Encoding(bom); + string text = encoding.GetString(bytes, bom ? 3 : 0, bytes.Length - (bom ? 3 : 0)); + string solutionDir = Path.GetDirectoryName(solutionFile); + bool isCompanion(string relativePath) => IsCompanionPath(solutionDir, relativePath, companionCsprojPaths); + + string updated = solutionFile.EndsWith(".slnx", StringComparison.OrdinalIgnoreCase) + ? RemoveFromSlnx(text, isCompanion) + : RemoveFromSln(text, isCompanion); + if (updated == null || updated == text) + { + return; + } + File.WriteAllBytes(solutionFile, encoding.GetPreamble().Concat(encoding.GetBytes(updated)).ToArray()); + Logger.Information($"SolutionFileCleanup: removed the companion projects from {solutionFile}"); + } + catch (Exception ex) + { + // Best-effort: at worst VS reports the project as not found on the next open, and + // SolutionWiring.EnsureProjectInSolution removes the stale entry on the next View Designer + Logger.Exception(ex, $"SolutionFileCleanup: could not clean {solutionFile}"); + } + } + + private static bool IsCompanionPath(string solutionDir, string relativePath, ICollection companionCsprojPaths) + { + if (string.IsNullOrEmpty(relativePath)) + { + return false; + } + try + { + string fullPath = Path.GetFullPath(Path.Combine(solutionDir, relativePath.Replace('/', '\\'))); + return companionCsprojPaths.Any(p => string.Equals(p, fullPath, StringComparison.OrdinalIgnoreCase)); + } + catch (Exception) + { + // Not a valid path, so not a companion + return false; + } + } + + /// + /// .slnx: removes the <Project Path="..."> elements of the companions, then the Solution Folder + /// (<Folder Name="/Shadow Designer (generated)/">) when it has no other content. + /// + private static string RemoveFromSlnx(string text, Func isCompanion) + { + var doc = XDocument.Parse(text, LoadOptions.PreserveWhitespace); + var projects = doc.Descendants("Project").Where(p => isCompanion((string)p.Attribute("Path"))).ToList(); + if (projects.Count == 0) + { + return null; + } + foreach (var project in projects) + { + RemoveWithIndentation(project); + } + string folderName = "/" + SolutionWiring.ShadowDesignerFolderName + "/"; + foreach (var folder in doc.Descendants("Folder").Where(f => (string)f.Attribute("Name") == folderName && !f.HasElements).ToList()) + { + RemoveWithIndentation(folder); + } + + var settings = new XmlWriterSettings + { + OmitXmlDeclaration = doc.Declaration == null, + Encoding = new UTF8Encoding(false), + // XML parsing turned CRLF into LF in the whitespace nodes + NewLineChars = text.Contains("\r\n") ? "\r\n" : "\n", + NewLineHandling = NewLineHandling.Replace, + }; + var builder = new StringBuilder(); + using (var writer = XmlWriter.Create(new StringWriter(builder), settings)) + { + doc.Save(writer); + } + string result = builder.ToString(); + if (doc.Declaration != null) + { + // A StringWriter makes XmlWriter write encoding="utf-16": keep the original declaration + int end = result.IndexOf("?>", StringComparison.Ordinal); + result = doc.Declaration.ToString() + result.Substring(end + 2); + } + // Keep a final line break the original had + if (text.EndsWith("\n") && !result.EndsWith("\n")) + { + result += settings.NewLineChars; + } + return result; + } + + /// Removes the element and the whitespace before it, so no empty line is left. + private static void RemoveWithIndentation(XElement element) + { + if (element.PreviousNode is XText indentation && string.IsNullOrWhiteSpace(indentation.Value)) + { + indentation.Remove(); + } + element.Remove(); + } + + private static readonly Regex SlnProjectLine = new Regex( + @"^Project\(""(?\{[^}]+\})""\)\s*=\s*""(?[^""]*)""\s*,\s*""(?[^""]*)""\s*,\s*""(?\{[^}]+\})""", + RegexOptions.IgnoreCase); + + /// + /// .sln: removes the Project...EndProject blocks of the companions and every line that names their GUID + /// (configurations, NestedProjects), then the Solution Folder when no project is nested in it anymore. + /// + private static string RemoveFromSln(string text, Func isCompanion) + { + string newLine = text.Contains("\r\n") ? "\r\n" : "\n"; + var lines = text.Split(new[] { newLine }, StringSplitOptions.None).ToList(); + + var companionGuids = new HashSet(StringComparer.OrdinalIgnoreCase); + string folderGuid = null; + foreach (string line in lines) + { + var match = SlnProjectLine.Match(line); + if (!match.Success) + { + continue; + } + if (isCompanion(match.Groups["path"].Value)) + { + companionGuids.Add(match.Groups["guid"].Value); + } + else if (string.Equals(match.Groups["type"].Value, SolutionFolderTypeGuid, StringComparison.OrdinalIgnoreCase) && + match.Groups["name"].Value == SolutionWiring.ShadowDesignerFolderName) + { + folderGuid = match.Groups["guid"].Value; + } + } + if (companionGuids.Count == 0) + { + return null; + } + RemoveSlnProjects(lines, companionGuids); + + // NestedProjects lines read "{child} = {parent}": the folder is empty when it is nobody's parent anymore + if (folderGuid != null && !lines.Any(l => l.Trim().EndsWith("= " + folderGuid, StringComparison.OrdinalIgnoreCase))) + { + RemoveSlnProjects(lines, new HashSet(StringComparer.OrdinalIgnoreCase) { folderGuid }); + } + RemoveEmptyNestedProjectsSection(lines); + return string.Join(newLine, lines); + } + + private static void RemoveSlnProjects(List lines, HashSet guids) + { + for (int i = 0; i < lines.Count; i++) + { + var match = SlnProjectLine.Match(lines[i]); + if (match.Success && guids.Contains(match.Groups["guid"].Value)) + { + int end = i; + while (end < lines.Count && lines[end].Trim() != "EndProject") + { + end++; + } + lines.RemoveRange(i, Math.Min(end, lines.Count - 1) - i + 1); + i--; + } + else if (!match.Success && guids.Any(g => lines[i].TrimStart().StartsWith(g, StringComparison.OrdinalIgnoreCase))) + { + // "{guid}.Debug|Any CPU.ActiveCfg = ..." and "{guid} = {parent}" + lines.RemoveAt(i); + i--; + } + } + } + + private static void RemoveEmptyNestedProjectsSection(List lines) + { + for (int i = 0; i < lines.Count - 1; i++) + { + if (lines[i].Trim().StartsWith("GlobalSection(NestedProjects)", StringComparison.OrdinalIgnoreCase) && + lines[i + 1].Trim() == "EndGlobalSection") + { + lines.RemoveRange(i, 2); + return; + } + } + } + } +} diff --git a/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionWiring.cs b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionWiring.cs index 86a201b475..cb64f87a1b 100644 --- a/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionWiring.cs +++ b/src/VisualStudio/ProjectSystemCPS/ShadowDesigner/SolutionWiring.cs @@ -44,11 +44,57 @@ public static void EnsureProjectInSolution(string csprojPath) throw new InvalidOperationException("The solution service does not support adding companion projects."); } + // Adding the companion makes the solution dirty, and so does removing it on close + // (ShadowDesignerCleanup). When nothing else is unsaved, both are saved right away, so the + // companion never makes VS ask to save the solution. + bool wasDirty = IsSolutionDirty(solution); + RemoveStaleHierarchy(solution, csprojPath); RemoveStaleProjectItem(solution, Path.GetFileNameWithoutExtension(csprojPath)); var folder = EnsureSolutionFolder(solution, ShadowDesignerFolderName); ErrorHandler.ThrowOnFailure(solution6.AddExistingProject(csprojPath, folder, out _)); + + if (!wasDirty) + { + SaveSolutionFile(solution, "companion added"); + } + } + + /// True when the solution has changes that are not saved yet. + internal static bool IsSolutionDirty(IVsSolution vsSolution) + { + ThreadHelper.ThrowIfNotOnUIThread(); + return ErrorHandler.Succeeded(vsSolution.GetProperty((int)__VSPROPID.VSPROPID_IsSolutionDirty, out object dirty)) && + dirty is bool isDirty && isDirty; + } + + /// The full path of the solution file, or null for a solution that was never saved. + internal static string GetSolutionFile(IVsSolution vsSolution) + { + ThreadHelper.ThrowIfNotOnUIThread(); + if (ErrorHandler.Failed(vsSolution.GetSolutionInfo(out _, out string solutionFile, out _)) || + string.IsNullOrEmpty(solutionFile) || !File.Exists(solutionFile)) + { + return null; + } + return solutionFile; + } + + /// + /// Saves the solution file without asking. Skipped for a solution that was never saved, where saving + /// would show the Save As dialog. + /// + internal static void SaveSolutionFile(IVsSolution vsSolution, string reason) + { + ThreadHelper.ThrowIfNotOnUIThread(); + string solutionFile = GetSolutionFile(vsSolution); + if (solutionFile == null) + { + return; + } + int hr = vsSolution.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_SaveIfDirty, null, 0); + Logger.Information($"SolutionWiring: saved {solutionFile} ({reason}), hr=0x{hr:X8}"); } ///