diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e3ad28..3795d56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,40 +1,58 @@ -# Code Editor Package for Visual Studio - -## [1.0.11] - 2019-05-21 - -Fix detection of visual studio for mac installation. - -## [1.0.10] - 2019-05-04 - -Fix ignored comintegration executable - - -## [1.0.9] - 2019-03-05 - -Updated MonoDevelop support, to pass correct arguments, and not import VSTU plugin -Use release build of COMIntegration for Visual Studio - - -## [1.0.7] - 2019-04-30 - -Ensure asset database is refreshed when generating csproj and solution files. - -## [1.0.6] - 2019-04-27 - -Add support for generating all csproj files. - -## [1.0.5] - 2019-04-18 - -Fix relative package paths. -Fix opening editor on mac. - -## [1.0.4] - 2019-04-12 - -- Fixing null reference issue for callbacks to AssetPostProcessor. -- Ensure Path.GetFullPath does not get an empty string. - -## [1.0.3] - 2019-01-01 - -### This is the first release of *Unity Package visualstudio_editor*. - -Using the newly created api to integrate Visual Studio with Unity. +# Code Editor Package for Visual Studio + +## [2.0.0] - 2019-11-06 + +- Improved Visual Studio and Visual Studio for Mac automatic discovery +- Added support for the VSTU messaging system (start/stop features from Visual Studio) +- Added support for solution roundtrip (preserves references to external projects and solution properties) +- Added support for VSTU Analyzers (requires Visual Studio 2019 16.3, Visual Studio for Mac 8.3) +- Added a warning when using legacy pdb symbol files. +- Fixed issues while Opening Visual Studio on Windows +- Fixed issues while Opening Visual Studio on Mac + +## [1.1.1] - 2019-05-29 + +Fix Bridge assembly loading with non VS2017 editors + +## [1.1.0] - 2019-05-27 + +Move internal extension handling to package. + +## [1.0.11] - 2019-05-21 + +Fix detection of visual studio for mac installation. + +## [1.0.10] - 2019-05-04 + +Fix ignored comintegration executable + + +## [1.0.9] - 2019-03-05 + +Updated MonoDevelop support, to pass correct arguments, and not import VSTU plugin +Use release build of COMIntegration for Visual Studio + + +## [1.0.7] - 2019-04-30 + +Ensure asset database is refreshed when generating csproj and solution files. + +## [1.0.6] - 2019-04-27 + +Add support for generating all csproj files. + +## [1.0.5] - 2019-04-18 + +Fix relative package paths. +Fix opening editor on mac. + +## [1.0.4] - 2019-04-12 + +- Fixing null reference issue for callbacks to AssetPostProcessor. +- Ensure Path.GetFullPath does not get an empty string. + +## [1.0.3] - 2019-01-01 + +### This is the first release of *Unity Package visualstudio_editor*. + +Using the newly created api to integrate Visual Studio with Unity. diff --git a/CHANGELOG.md.meta b/CHANGELOG.md.meta index eb54a61..069c9bf 100644 --- a/CHANGELOG.md.meta +++ b/CHANGELOG.md.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: 6022bdd5b2896a54f94123b812705321 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 6022bdd5b2896a54f94123b812705321 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f0005f6..6443a82 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ -# Contributing - -## All contributions are subject to the [Unity Contribution Agreement(UCA)](https://unity3d.com/legal/licenses/Unity_Contribution_Agreement) -By making a pull request, you are confirming agreement to the terms and conditions of the UCA, including that your Contributions are your original creation and that you have complete right and authority to make your Contributions. - +# Contributing + +## All contributions are subject to the [Unity Contribution Agreement(UCA)](https://unity3d.com/legal/licenses/Unity_Contribution_Agreement) and [Microsoft Contributor License Agreement (CLA)](https://cla.opensource.microsoft.com/) +By making a pull request, you are confirming agreement to the terms and conditions of the UCA and CLA, including that your contributions are your original creation and that you have complete right and authority to make your contributions. + ## Once you have a change ready following these ground rules. Simply make a pull request \ No newline at end of file diff --git a/CONTRIBUTING.md.meta b/CONTRIBUTING.md.meta index 08fa9e7..61c088c 100644 --- a/CONTRIBUTING.md.meta +++ b/CONTRIBUTING.md.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: cd78ce5b75b8be84d8b94cd99903161f -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: cd78ce5b75b8be84d8b94cd99903161f +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Documentation~/README.md b/Documentation~/README.md index 4b5de36..f2ae703 100644 --- a/Documentation~/README.md +++ b/Documentation~/README.md @@ -1,4 +1,4 @@ -# Code Editor Package for Visual Studio - -This package is not intended to be modified by users. +# Code Editor Package for Visual Studio + +This package is not intended to be modified by users. Nor does it provide any api intended to be included in user projects. \ No newline at end of file diff --git a/Editor.meta b/Editor.meta index 7b6d700..5683b3b 100644 --- a/Editor.meta +++ b/Editor.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: 4a707af59e3522d43afe34dfc4429b86 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 4a707af59e3522d43afe34dfc4429b86 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/COMIntegration.meta b/Editor/COMIntegration.meta index c36cceb..bf3a993 100644 --- a/Editor/COMIntegration.meta +++ b/Editor/COMIntegration.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: 36422aa067e092e45b9820da2ee3e728 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 36422aa067e092e45b9820da2ee3e728 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/COMIntegration/Release.meta b/Editor/COMIntegration/Release.meta index 3ebb587..c7e9b68 100644 --- a/Editor/COMIntegration/Release.meta +++ b/Editor/COMIntegration/Release.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: 41b2d972bdac29e4a89ef08b3b52c248 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 41b2d972bdac29e4a89ef08b3b52c248 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/COMIntegration/Release/COMIntegration.dom b/Editor/COMIntegration/Release/COMIntegration.dom deleted file mode 100644 index 198a412..0000000 Binary files a/Editor/COMIntegration/Release/COMIntegration.dom and /dev/null differ diff --git a/Editor/COMIntegration/Release/COMIntegration.exe b/Editor/COMIntegration/Release/COMIntegration.exe new file mode 100644 index 0000000..a644e95 Binary files /dev/null and b/Editor/COMIntegration/Release/COMIntegration.exe differ diff --git a/Editor/COMIntegration/Release/COMIntegration.dom.meta b/Editor/COMIntegration/Release/COMIntegration.exe.meta similarity index 95% rename from Editor/COMIntegration/Release/COMIntegration.dom.meta rename to Editor/COMIntegration/Release/COMIntegration.exe.meta index e927985..43d762c 100644 --- a/Editor/COMIntegration/Release/COMIntegration.dom.meta +++ b/Editor/COMIntegration/Release/COMIntegration.exe.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: cb67edc1800c2ec4ba8dfb1cf0dfc84a -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: cb67edc1800c2ec4ba8dfb1cf0dfc84a +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Discovery.cs b/Editor/Discovery.cs index 7a0c5b9..e6f56cd 100644 --- a/Editor/Discovery.cs +++ b/Editor/Discovery.cs @@ -1,275 +1,165 @@ -using System; -using System.IO; -using System.Collections.Generic; -using System.Linq; -using Unity.CodeEditor; -using UnityEngine; -using UnityEditor; -using System.Diagnostics; -using Microsoft.Win32; - -namespace VisualStudioEditor -{ - public interface IDiscovery { - CodeEditor.Installation[] PathCallback(); - } - - public class Discovery : IDiscovery { - internal static string VisualStudioVersionToNiceName(VisualStudioVersion version) - { - switch (version) - { - case VisualStudioVersion.Invalid: return "Invalid Version"; - case VisualStudioVersion.VisualStudio2008: return "Visual Studio 2008"; - case VisualStudioVersion.VisualStudio2010: return "Visual Studio 2010"; - case VisualStudioVersion.VisualStudio2012: return "Visual Studio 2012"; - case VisualStudioVersion.VisualStudio2013: return "Visual Studio 2013"; - case VisualStudioVersion.VisualStudio2015: return "Visual Studio 2015"; - case VisualStudioVersion.VisualStudio2017: return "Visual Studio 2017"; - case VisualStudioVersion.VisualStudio2019: return "Visual Studio 2019"; - default: - throw new ArgumentOutOfRangeException(nameof(version), version, null); - } - } - - public CodeEditor.Installation[] PathCallback() - { - try - { - if (VSEditor.IsWindows) - { - return GetInstalledVisualStudios().Select(pair => new CodeEditor.Installation - { - Path = pair.Value[0], - Name = VisualStudioVersionToNiceName(pair.Key) - }).ToArray(); - } - if (VSEditor.IsOSX) - { - var installationList = new List(); - AddIfDirectoryExists("Visual Studio", "/Applications/Visual Studio.app", installationList); - AddIfDirectoryExists("Visual Studio (Preview)", "/Applications/Visual Studio (Preview).app", installationList); - return installationList.ToArray(); - } - } - catch (Exception ex) - { - UnityEngine.Debug.Log($"Error detecting Visual Studio installations: {ex.Message}{Environment.NewLine}{ex.StackTrace}"); - } - return new CodeEditor.Installation[0]; - } - - void AddIfDirectoryExists(string name, string path, List installations) - { - if (Directory.Exists(path)) - { - installations.Add(new CodeEditor.Installation { Name = name, Path = path }); - } - } - - static string GetRegistryValue(string path, string key) - { - try - { - return Registry.GetValue(path, key, null) as string; - } - catch (Exception) - { - return ""; - } - } - - /// - /// Derives the Visual Studio installation path from the debugger path - /// - /// - /// The Visual Studio installation path (to devenv.exe) - /// - /// - /// The debugger path from the windows registry - /// - static string DeriveVisualStudioPath(string debuggerPath) - { - string startSentinel = DeriveProgramFilesSentinel(); - string endSentinel = "Common7"; - bool started = false; - string[] tokens = debuggerPath.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); - - string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - - // Walk directories in debugger path, chop out "Program Files\INSTALLATION\PATH\HERE\Common7" - foreach (var token in tokens) - { - if (!started && string.Equals(startSentinel, token, StringComparison.OrdinalIgnoreCase)) - { - started = true; - continue; - } - if (started) - { - path = Path.Combine(path, token); - if (string.Equals(endSentinel, token, StringComparison.OrdinalIgnoreCase)) - break; - } - } - - return Path.Combine(path, "IDE", "devenv.exe"); - } - - /// - /// Derives the program files sentinel for grabbing the VS installation path. - /// - /// - /// From a path like 'c:\Archivos de programa (x86)', returns 'Archivos de programa' - /// - static string DeriveProgramFilesSentinel() - { - string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) - .Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) - .LastOrDefault(); - - if (!string.IsNullOrEmpty(path)) - { - // This needs to be the "real" Program Files regardless of 64bitness - int index = path.LastIndexOf("(x86)"); - if (0 <= index) - path = path.Remove(index); - return path.TrimEnd(); - } - - return "Program Files"; - } - - public static void ParseRawDevEnvPaths(string[] rawDevEnvPaths, Dictionary versions) - { - if (rawDevEnvPaths == null) - { - return; - } - - var v2017 = rawDevEnvPaths.Where(path => path.Contains("2017")).ToArray(); - var v2019 = rawDevEnvPaths.Where(path => path.Contains("2019")).ToArray(); - - if (v2017.Length > 0) - { - versions[VisualStudioVersion.VisualStudio2017] = v2017; - } - - if (v2019.Length > 0) - { - versions[VisualStudioVersion.VisualStudio2019] = v2019; - } - } - - /// - /// Detects Visual Studio installations using the Windows registry - /// - /// - /// The detected Visual Studio installations - /// - public static Dictionary GetInstalledVisualStudios() - { - var versions = new Dictionary(); - - if (VSEditor.IsWindows) - { - foreach (VisualStudioVersion version in Enum.GetValues(typeof(VisualStudioVersion))) - { - if (version > VisualStudioVersion.VisualStudio2015) - continue; - - try - { - // Try COMNTOOLS environment variable first - FindLegacyVisualStudio(version, versions); - } - catch (Exception e) - { - UnityEngine.Debug.LogError($"VS: {e.Message}"); - } - } - - var raw = FindVisualStudioDevEnvPaths(); - - ParseRawDevEnvPaths(raw.ToArray(), versions); - } - - return versions; - } - - static void FindLegacyVisualStudio(VisualStudioVersion version, Dictionary versions) - { - string key = Environment.GetEnvironmentVariable($"VS{(int)version}0COMNTOOLS"); - if (!string.IsNullOrEmpty(key)) - { - string path = Path.Combine(key, "..", "IDE", "devenv.exe"); - if (File.Exists(path)) - { - versions[version] = new[] { path }; - return; - } - } - - // Try the proper registry key - key = GetRegistryValue( - $@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\{(int)version}.0", "InstallDir"); - - // Try to fallback to the 32bits hive - if (string.IsNullOrEmpty(key)) - key = GetRegistryValue( - $@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\{(int)version}.0", "InstallDir"); - - if (!string.IsNullOrEmpty(key)) - { - string path = Path.Combine(key, "devenv.exe"); - if (File.Exists(path)) - { - versions[version] = new[] { path }; - return; - } - } - - // Fallback to debugger key - key = GetRegistryValue( - // VS uses this key for the local debugger path - $@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\{(int)version}.0\Debugger", "FEQARuntimeImplDll"); - if (!string.IsNullOrEmpty(key)) - { - string path = DeriveVisualStudioPath(key); - if (!string.IsNullOrEmpty(path) && File.Exists(path)) - versions[version] = new[] { DeriveVisualStudioPath(key) }; - } - } - - static IEnumerable FindVisualStudioDevEnvPaths() - { - string asset = AssetDatabase.FindAssets("VSWhere a:packages").Select(AssetDatabase.GUIDToAssetPath).FirstOrDefault(assetPath => assetPath.Contains("vswhere.exe")); - if (string.IsNullOrWhiteSpace(asset)) // This may be called too early where the asset database has not replicated this information yet. - { - yield break; - } - UnityEditor.PackageManager.PackageInfo packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(asset); - var progpath = packageInfo.resolvedPath + asset.Substring("Packages/com.unity.ide.visualstudio".Length); - var process = new Process - { - StartInfo = new ProcessStartInfo - { - FileName = progpath, - Arguments = "-prerelease -property productPath", - UseShellExecute = false, - CreateNoWindow = true, - RedirectStandardOutput = true, - RedirectStandardError = true, - } - }; - - process.Start(); - process.WaitForExit(); - - while (!process.StandardOutput.EndOfStream) - { - yield return process.StandardOutput.ReadLine(); - } - } - } -} \ No newline at end of file +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Unity Technologies. + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Collections.Generic; +using UnityEngine; +using System.Diagnostics; +using System.Text.RegularExpressions; +using System.Linq; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal static class Discovery + { + public static IEnumerable GetVisualStudioInstallations() + { + if (VisualStudioEditor.IsWindows) + { + foreach (var installation in QueryVsWhere()) + yield return installation; + } + + if (VisualStudioEditor.IsOSX) + { + var candidates = Directory.EnumerateDirectories("/Applications", "*.app"); + foreach (var candidate in candidates) + { + if (TryDiscoverInstallation(candidate, out var installation)) + yield return installation; + } + } + } + + private static bool IsCandidateToDiscovery(string path) + { + if (File.Exists(path) && VisualStudioEditor.IsWindows && Regex.IsMatch(path, "devenv.exe$", RegexOptions.IgnoreCase)) + return true; + + if (Directory.Exists(path) && VisualStudioEditor.IsOSX && Regex.IsMatch(path, "Visual\\s?Studio(?!.*Code.*).*.app$", RegexOptions.IgnoreCase)) + return true; + + return false; + } + + public static bool TryDiscoverInstallation(string editorPath, out VisualStudioInstallation installation) + { + installation = null; + + if (string.IsNullOrEmpty(editorPath)) + return false; + + if (!IsCandidateToDiscovery(editorPath)) + return false; + + // On windows we use the executable directly, so we can query extra information + var fvi = editorPath; + + // On Mac we use the .app folder, so we need to access to main assembly + if (VisualStudioEditor.IsOSX) + fvi = Path.Combine(editorPath, "Contents", "Resources", "lib", "monodevelop", "bin", "VisualStudio.exe"); + + if (!File.Exists(fvi)) + return false; + + // VS preview are not using the isPrerelease flag so far + // On Windows FileDescription contains "Preview", but not on Mac + var vi = FileVersionInfo.GetVersionInfo(fvi); + var version = new Version(vi.ProductVersion); + var isPrerelease = vi.IsPreRelease || string.Concat(editorPath, "/" + vi.FileDescription).ToLower().Contains("preview"); + + installation = new VisualStudioInstallation() + { + IsPrerelease = isPrerelease, + Name = $"{vi.FileDescription}{(isPrerelease && VisualStudioEditor.IsOSX ? " Preview" : string.Empty)} [{version.ToString(3)}]", + Path = editorPath, + Version = version + }; + return true; + } + + #region VsWhere Json Schema + #pragma warning disable CS0649 + [Serializable] + internal class VsWhereResult + { + public VsWhereEntry[] entries; + + public static VsWhereResult FromJson(string json) + { + return JsonUtility.FromJson("{ \"" + nameof(VsWhereResult.entries) + "\": " + json + " }"); + } + + public IEnumerable ToVisualStudioInstallations() + { + foreach(var entry in entries) + { + yield return new VisualStudioInstallation() + { + Name = $"{entry.displayName} [{entry.catalog.productDisplayVersion}]", + Path = entry.productPath, + IsPrerelease = entry.isPrerelease, + Version = Version.Parse(entry.catalog.buildVersion) + }; + } + } + } + + [Serializable] + internal class VsWhereEntry + { + public string displayName; + public bool isPrerelease; + public string productPath; + public VsWhereCatalog catalog; + } + + [Serializable] + internal class VsWhereCatalog + { + public string productDisplayVersion; // non parseable like "16.3.0 Preview 3.0" + public string buildVersion; + } + #pragma warning restore CS3021 + #endregion + + private static IEnumerable QueryVsWhere() + { + var progpath = FileUtility + .FindPackageAssetFullPath("VSWhere a:packages", "vswhere.exe") + .FirstOrDefault(); + + if (string.IsNullOrWhiteSpace(progpath)) + return Enumerable.Empty(); + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = progpath, + Arguments = "-prerelease -format json", + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + } + }; + + using (process) + { + var json = string.Empty; + + process.OutputDataReceived += (o, e) => json += e.Data; + process.Start(); + process.BeginOutputReadLine(); + process.WaitForExit(); + + var result = VsWhereResult.FromJson(json); + return result.ToVisualStudioInstallations(); + } + } + } +} diff --git a/Editor/Discovery.cs.meta b/Editor/Discovery.cs.meta index 0dfad1c..0954edf 100644 --- a/Editor/Discovery.cs.meta +++ b/Editor/Discovery.cs.meta @@ -1,11 +1,11 @@ -fileFormatVersion: 2 -guid: abe003ac6fee32e4892100a78f555011 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: abe003ac6fee32e4892100a78f555011 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/FileUtility.cs b/Editor/FileUtility.cs new file mode 100644 index 0000000..9e04ac4 --- /dev/null +++ b/Editor/FileUtility.cs @@ -0,0 +1,92 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Unity Technologies. + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal static class FileUtility + { + public const char WinSeparator = '\\'; + public const char UnixSeparator = '/'; + + // Safe for packages as we use packageInfo.resolvedPath, so this should work in library package cache as well + public static string[] FindPackageAssetFullPath(string assetfilter, string filefilter) + { + return AssetDatabase.FindAssets(assetfilter) + .Select(AssetDatabase.GUIDToAssetPath) + .Where(assetPath => assetPath.Contains(filefilter)) + .Select(asset => + { + var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(asset); + return Normalize(packageInfo.resolvedPath + asset.Substring(packageInfo.assetPath.Length)); + }) + .ToArray(); + } + + public static string GetAssetFullPath(string asset) + { + var basePath = Path.GetFullPath(Path.Combine(Application.dataPath, "..")); + return Path.GetFullPath(Path.Combine(basePath, Normalize(asset))); + } + + public static string Normalize(string path) + { + if (string.IsNullOrEmpty(path)) + return path; + + if (Path.DirectorySeparatorChar == WinSeparator) + path = path.Replace(UnixSeparator, WinSeparator); + + return path.Replace(string.Concat(WinSeparator, WinSeparator), WinSeparator.ToString()); + } + + internal static bool IsFileInProjectDirectory(string fileName) + { + var basePath = Path.GetFullPath(Path.Combine(Application.dataPath, "..")); + fileName = Normalize(fileName); + + if (!Path.IsPathRooted(fileName)) + fileName = Path.Combine(basePath, fileName); + + return string.Equals(Path.GetDirectoryName(fileName), basePath, StringComparison.OrdinalIgnoreCase); + } + + public static string FileNameWithoutExtension(string path) + { + if (string.IsNullOrEmpty(path)) + { + return ""; + } + + var indexOfDot = -1; + var indexOfSlash = 0; + for (var i = path.Length - 1; i >= 0; i--) + { + if (indexOfDot == -1 && path[i] == '.') + { + indexOfDot = i; + } + + if (indexOfSlash == 0 && path[i] == '/' || path[i] == '\\') + { + indexOfSlash = i + 1; + break; + } + } + + if (indexOfDot == -1) + { + indexOfDot = path.Length - 1; + } + + return path.Substring(indexOfSlash, indexOfDot - indexOfSlash); + } + } +} diff --git a/Editor/Utility.cs.meta b/Editor/FileUtility.cs.meta similarity index 95% rename from Editor/Utility.cs.meta rename to Editor/FileUtility.cs.meta index 7cc03e7..f14ab79 100644 --- a/Editor/Utility.cs.meta +++ b/Editor/FileUtility.cs.meta @@ -1,11 +1,11 @@ -fileFormatVersion: 2 -guid: 6f1dc05fb6e7d3e4f89ae9ca482735be -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 6f1dc05fb6e7d3e4f89ae9ca482735be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature.meta b/Editor/Messaging.meta similarity index 73% rename from Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature.meta rename to Editor/Messaging.meta index 10f6d91..6c8374a 100644 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature.meta +++ b/Editor/Messaging.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: 55aae143147983c4ca41af0f79695248 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 2f820130c86c28547a0f1a2f4c73155b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/Deserializer.cs b/Editor/Messaging/Deserializer.cs new file mode 100644 index 0000000..039dc8f --- /dev/null +++ b/Editor/Messaging/Deserializer.cs @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Text; + +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal class Deserializer + { + private readonly BinaryReader _reader; + + // Max UDP packet size is 65507 + private const int MaxStringLength = 65000; + + public Deserializer(byte[] buffer) + { + _reader = new BinaryReader(new MemoryStream(buffer)); + } + + public int ReadInt32() + { + return _reader.ReadInt32(); + } + + public string ReadString() + { + var length = ReadInt32(); + return length > 0 && length <= MaxStringLength + ? Encoding.UTF8.GetString(_reader.ReadBytes(length)) + : ""; + } + + public bool CanReadMore() + { + return _reader.BaseStream.Position < _reader.BaseStream.Length; + } + } +} diff --git a/Editor/VSInitializer.cs.meta b/Editor/Messaging/Deserializer.cs.meta similarity index 80% rename from Editor/VSInitializer.cs.meta rename to Editor/Messaging/Deserializer.cs.meta index 508631f..9fc116b 100644 --- a/Editor/VSInitializer.cs.meta +++ b/Editor/Messaging/Deserializer.cs.meta @@ -1,11 +1,11 @@ -fileFormatVersion: 2 -guid: c70a64eb158b0104bb528b12e1d80c2a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 3eda7a83649158546826efb3ffe6c1e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/ExceptionEventArgs.cs b/Editor/Messaging/ExceptionEventArgs.cs new file mode 100644 index 0000000..617c71f --- /dev/null +++ b/Editor/Messaging/ExceptionEventArgs.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal class ExceptionEventArgs + { + public Exception Exception { get; } + + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/Editor/Messaging/ExceptionEventArgs.cs.meta b/Editor/Messaging/ExceptionEventArgs.cs.meta new file mode 100644 index 0000000..f53f8a3 --- /dev/null +++ b/Editor/Messaging/ExceptionEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 917a51fff055ce547b4ad1215321f3da +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/Message.cs b/Editor/Messaging/Message.cs new file mode 100644 index 0000000..77eae14 --- /dev/null +++ b/Editor/Messaging/Message.cs @@ -0,0 +1,23 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Globalization; +using System.Net; + +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal class Message + { + public MessageType Type { get; set; } + + public string Value { get; set; } + + public IPEndPoint Origin { get; set; } + + public override string ToString() + { + return string.Format(CultureInfo.InvariantCulture, "", Type, Value); + } + } +} diff --git a/Editor/Messaging/Message.cs.meta b/Editor/Messaging/Message.cs.meta new file mode 100644 index 0000000..2163640 --- /dev/null +++ b/Editor/Messaging/Message.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de1c9ea7b82c9904d9e5fba2ee70a998 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/MessageEventArgs.cs b/Editor/Messaging/MessageEventArgs.cs new file mode 100644 index 0000000..10ffb93 --- /dev/null +++ b/Editor/Messaging/MessageEventArgs.cs @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal class MessageEventArgs + { + public Message Message + { + get; + } + + public MessageEventArgs(Message message) + { + Message = message; + } + } +} diff --git a/Editor/Messaging/MessageEventArgs.cs.meta b/Editor/Messaging/MessageEventArgs.cs.meta new file mode 100644 index 0000000..e09b3e4 --- /dev/null +++ b/Editor/Messaging/MessageEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 275143c81d816ef4286fdc67aabc20c8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/MessageType.cs b/Editor/Messaging/MessageType.cs new file mode 100644 index 0000000..9850e68 --- /dev/null +++ b/Editor/Messaging/MessageType.cs @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal enum MessageType + { + None = 0, + + Ping, + Pong, + + Play, + Stop, + Pause, + Unpause, + + Build, + Refresh, + + Info, + Error, + Warning, + + Open, + Opened, + + Version, + UpdatePackage, + + ProjectPath, + } +} diff --git a/Editor/Messaging/MessageType.cs.meta b/Editor/Messaging/MessageType.cs.meta new file mode 100644 index 0000000..ae0d328 --- /dev/null +++ b/Editor/Messaging/MessageType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f3edbdc86577af648a23263aa75161e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/Messenger.cs b/Editor/Messaging/Messenger.cs new file mode 100644 index 0000000..49ae086 --- /dev/null +++ b/Editor/Messaging/Messenger.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Net; +using System.Net.Sockets; + +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal class Messager : IDisposable + { + public event EventHandler ReceiveMessage; + public event EventHandler MessagerException; + + private readonly UdpSocket _socket; + private readonly object _disposeLock = new object(); + private bool _disposed; + + protected Messager(int port) + { + _socket = new UdpSocket(); + _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false); + _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + _socket.Bind(IPAddress.Any, port); + + BeginReceiveMessage(); + } + + private void BeginReceiveMessage() + { + var buffer = new byte[UdpSocket.BufferSize]; + var any = UdpSocket.Any(); + + try + { + lock (_disposeLock) + { + if (_disposed) + return; + + _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref any, ReceiveMessageCallback, buffer); + } + } + catch (SocketException se) + { + MessagerException?.Invoke(this, new ExceptionEventArgs(se)); + + BeginReceiveMessage(); + } + catch (ObjectDisposedException) + { + } + } + + private void ReceiveMessageCallback(IAsyncResult result) + { + try + { + var endPoint = UdpSocket.Any(); + + lock (_disposeLock) + { + if (_disposed) + return; + + _socket.EndReceiveFrom(result, ref endPoint); + } + + var message = DeserializeMessage(UdpSocket.BufferFor(result)); + if (message != null) + { + message.Origin = (IPEndPoint)endPoint; + ReceiveMessage?.Invoke(this, new MessageEventArgs(message)); + } + } + catch (ObjectDisposedException) + { + return; + } + catch (Exception e) + { + RaiseMessagerException(e); + } + + BeginReceiveMessage(); + } + + private void RaiseMessagerException(Exception e) + { + MessagerException?.Invoke(this, new ExceptionEventArgs(e)); + } + + private static Message MessageFor(MessageType type, string value) + { + return new Message { Type = type, Value = value }; + } + + public void SendMessage(IPEndPoint target, MessageType type, string value = "") + { + var message = MessageFor(type, value); + var buffer = SerializeMessage(message); + + try + { + lock (_disposeLock) + { + if (_disposed) + return; + + _socket.BeginSendTo(buffer, 0, Math.Min(buffer.Length, UdpSocket.BufferSize), SocketFlags.None, target, SendMessageCallback, null); + } + } + catch (SocketException se) + { + MessagerException?.Invoke(this, new ExceptionEventArgs(se)); + } + } + + private void SendMessageCallback(IAsyncResult result) + { + try + { + lock (_disposeLock) + { + if (_disposed) + return; + + _socket.EndSendTo(result); + } + } + catch (SocketException se) + { + MessagerException?.Invoke(this, new ExceptionEventArgs(se)); + } + catch (ObjectDisposedException) + { + } + } + + private static byte[] SerializeMessage(Message message) + { + var serializer = new Serializer(); + serializer.WriteInt32((int)message.Type); + serializer.WriteString(message.Value); + + return serializer.Buffer(); + } + + private static Message DeserializeMessage(byte[] buffer) + { + if (buffer.Length < 4) + return null; + + var deserializer = new Deserializer(buffer); + var type = (MessageType)deserializer.ReadInt32(); + var value = deserializer.ReadString(); + + return new Message { Type = type, Value = value }; + } + + public static Messager BindTo(int port) + { + return new Messager(port); + } + + public void Dispose() + { + lock (_disposeLock) + { + _disposed = true; + _socket.Close(); + } + } + } +} diff --git a/Editor/Messaging/Messenger.cs.meta b/Editor/Messaging/Messenger.cs.meta new file mode 100644 index 0000000..89d8421 --- /dev/null +++ b/Editor/Messaging/Messenger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e249ae353801f043a6e4173410c6152 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/Serializer.cs b/Editor/Messaging/Serializer.cs new file mode 100644 index 0000000..6324318 --- /dev/null +++ b/Editor/Messaging/Serializer.cs @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Text; + +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal class Serializer + { + private readonly MemoryStream _stream; + private readonly BinaryWriter _writer; + + public Serializer() + { + _stream = new MemoryStream(); + _writer = new BinaryWriter(_stream); + } + + public void WriteInt32(int i) + { + _writer.Write(i); + } + + public void WriteString(string s) + { + var bytes = Encoding.UTF8.GetBytes(s ?? ""); + if (bytes.Length > 0) + { + _writer.Write(bytes.Length); + _writer.Write(bytes); + } + else + _writer.Write(0); + } + + public byte[] Buffer() + { + return _stream.ToArray(); + } + } +} diff --git a/Editor/Messaging/Serializer.cs.meta b/Editor/Messaging/Serializer.cs.meta new file mode 100644 index 0000000..e664c14 --- /dev/null +++ b/Editor/Messaging/Serializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 369c09afe05d2c346af49faef943c773 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Messaging/UdpSocket.cs b/Editor/Messaging/UdpSocket.cs new file mode 100644 index 0000000..2432dba --- /dev/null +++ b/Editor/Messaging/UdpSocket.cs @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Net; +using System.Net.Sockets; + +namespace Microsoft.Unity.VisualStudio.Editor.Messaging +{ + internal class UdpSocket : Socket + { + public const int BufferSize = 1024 * 8; + + internal UdpSocket() + : base(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) + { + SetIOControl(); + } + + public void Bind(IPAddress address, int port = 0) + { + Bind(new IPEndPoint(address ?? IPAddress.Any, port)); + } + + private void SetIOControl() + { + if (!VisualStudioEditor.IsWindows) + return; + + try + { + const int SIO_UDP_CONNRESET = -1744830452; + + IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, new byte[0]); + } + catch + { + // fallback + } + } + + public static byte[] BufferFor(IAsyncResult result) + { + return (byte[])result.AsyncState; + } + + public static EndPoint Any() + { + return new IPEndPoint(IPAddress.Any, 0); + } + } +} diff --git a/Editor/Messaging/UdpSocket.cs.meta b/Editor/Messaging/UdpSocket.cs.meta new file mode 100644 index 0000000..8852c5a --- /dev/null +++ b/Editor/Messaging/UdpSocket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38cb3a4a17d2cfd41926da95ce675934 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins.meta b/Editor/Plugins.meta index 6e01768..676fbb1 100644 --- a/Editor/Plugins.meta +++ b/Editor/Plugins.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: 1e5abb64fdd0542b38f4dc1b60343e8a -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 1e5abb64fdd0542b38f4dc1b60343e8a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle.meta b/Editor/Plugins/AppleEventIntegration.bundle.meta similarity index 88% rename from Editor/Plugins/AppleEventIntegrationPlugin.bundle.meta rename to Editor/Plugins/AppleEventIntegration.bundle.meta index 991b7e7..e5b6825 100644 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle.meta +++ b/Editor/Plugins/AppleEventIntegration.bundle.meta @@ -1,28 +1,28 @@ -fileFormatVersion: 2 -guid: dd66e4390e06fc14e92b9822744f2fb1 -folderAsset: yes -PluginImporter: - externalObjects: {} - serializedVersion: 2 - iconMap: {} - executionOrder: {} - defineConstraints: [] - isPreloaded: 0 - isOverridable: 1 - isExplicitlyReferenced: 0 - validateReferences: 1 - platformData: - - first: - Any: - second: - enabled: 0 - settings: {} - - first: - Editor: Editor - second: - enabled: 1 - settings: - DefaultValueInitialized: true - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: a20df6e3467b24ed5b49c857ce39e096 +folderAsset: yes +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents.meta b/Editor/Plugins/AppleEventIntegration.bundle/Contents.meta similarity index 73% rename from Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents.meta rename to Editor/Plugins/AppleEventIntegration.bundle/Contents.meta index 1eeb0e2..03a3bfb 100644 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents.meta +++ b/Editor/Plugins/AppleEventIntegration.bundle/Contents.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: 179209ff257e808409c755d32ecf1086 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 058b02c03ea09473aab4dc5fc50af1ef +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/Info.plist b/Editor/Plugins/AppleEventIntegration.bundle/Contents/Info.plist similarity index 76% rename from Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/Info.plist rename to Editor/Plugins/AppleEventIntegration.bundle/Contents/Info.plist index 50c0c33..3b52961 100644 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/Info.plist +++ b/Editor/Plugins/AppleEventIntegration.bundle/Contents/Info.plist @@ -1,44 +1,42 @@ - - - - - BuildMachineOSBuild - 18E226 - CFBundleDevelopmentRegion - en - CFBundleExecutable - AppleEventIntegrationPlugin - CFBundleIdentifier - com.unity.AppleEventIntegrationPlugin - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - AppleEventIntegrationPlugin - CFBundlePackageType - BNDL - CFBundleShortVersionString - 1.0 - CFBundleSupportedPlatforms - - MacOSX - - CFBundleVersion - 1 - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 10E1001 - DTPlatformVersion - GM - DTSDKBuild - 18E219 - DTSDKName - macosx10.14 - DTXcode - 1020 - DTXcodeBuild - 10E1001 - NSHumanReadableCopyright - Copyright © 2019 Unity. All rights reserved. - - + + + + + BuildMachineOSBuild + 19B88 + CFBundleDevelopmentRegion + en + CFBundleExecutable + AppleEventIntegration + CFBundleIdentifier + com.unity.visualstudio.AppleEventIntegration + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + AppleEventIntegration + CFBundleShortVersionString + 1.0 + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 1 + DTCompiler + com.apple.compilers.llvm.clang.1_0 + DTPlatformBuild + 10E125 + DTPlatformVersion + GM + DTSDKBuild + 18E219 + DTSDKName + macosx10.14 + DTXcode + 1020 + DTXcodeBuild + 10E125 + NSHumanReadableCopyright + Copyright © 2019 Unity. All rights reserved. + + diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/Info.plist.meta b/Editor/Plugins/AppleEventIntegration.bundle/Contents/Info.plist.meta similarity index 71% rename from Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/Info.plist.meta rename to Editor/Plugins/AppleEventIntegration.bundle/Contents/Info.plist.meta index 4d47fc5..1f49dac 100644 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/Info.plist.meta +++ b/Editor/Plugins/AppleEventIntegration.bundle/Contents/Info.plist.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: d2694cce95579ec47a939a1a3efb8f33 -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 680cf1008b4284eddbb82ec4d76644a1 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS.meta b/Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS.meta similarity index 73% rename from Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS.meta rename to Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS.meta index 773ad15..8c69d7f 100644 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS.meta +++ b/Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: a0f0c231a0e381e4ea37a97a8e7837a0 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: ba4355216f6c44abbb17503872c42c97 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS/AppleEventIntegration b/Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS/AppleEventIntegration new file mode 100644 index 0000000..bf56250 Binary files /dev/null and b/Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS/AppleEventIntegration differ diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS/AppleEventIntegrationPlugin.meta b/Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS/AppleEventIntegration.meta similarity index 71% rename from Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS/AppleEventIntegrationPlugin.meta rename to Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS/AppleEventIntegration.meta index 7ddbcb5..52870b5 100644 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS/AppleEventIntegrationPlugin.meta +++ b/Editor/Plugins/AppleEventIntegration.bundle/Contents/MacOS/AppleEventIntegration.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: b94b55fbf62c6bd42a2f3edf2fd52f83 -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 4e53c7f7b5c7e4a3d890cb596ed56c22 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS/AppleEventIntegrationPlugin b/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS/AppleEventIntegrationPlugin deleted file mode 100644 index 3f59902..0000000 Binary files a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/MacOS/AppleEventIntegrationPlugin and /dev/null differ diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature/CodeResources b/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature/CodeResources deleted file mode 100644 index 06a6210..0000000 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature/CodeResources +++ /dev/null @@ -1,115 +0,0 @@ - - - - - files - - files2 - - rules - - ^Resources/ - - ^Resources/.*\.lproj/ - - optional - - weight - 1000 - - ^Resources/.*\.lproj/locversion.plist$ - - omit - - weight - 1100 - - ^Resources/Base\.lproj/ - - weight - 1010 - - ^version.plist$ - - - rules2 - - .*\.dSYM($|/) - - weight - 11 - - ^(.*/)?\.DS_Store$ - - omit - - weight - 2000 - - ^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/ - - nested - - weight - 10 - - ^.* - - ^Info\.plist$ - - omit - - weight - 20 - - ^PkgInfo$ - - omit - - weight - 20 - - ^Resources/ - - weight - 20 - - ^Resources/.*\.lproj/ - - optional - - weight - 1000 - - ^Resources/.*\.lproj/locversion.plist$ - - omit - - weight - 1100 - - ^Resources/Base\.lproj/ - - weight - 1010 - - ^[^/]+$ - - nested - - weight - 10 - - ^embedded\.provisionprofile$ - - weight - 20 - - ^version\.plist$ - - weight - 20 - - - - diff --git a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature/CodeResources.meta b/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature/CodeResources.meta deleted file mode 100644 index 7968517..0000000 --- a/Editor/Plugins/AppleEventIntegrationPlugin.bundle/Contents/_CodeSignature/CodeResources.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 8529f5a60acb8cd4395bd1cec74495ae -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Editor/ProjectGeneration.cs b/Editor/ProjectGeneration.cs index e50aadc..5ffc9e0 100644 --- a/Editor/ProjectGeneration.cs +++ b/Editor/ProjectGeneration.cs @@ -1,890 +1,1028 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; -using UnityEditor; -using UnityEditor.Compilation; -using UnityEditor.PackageManager; -using UnityEditor.Scripting.Compilers; -using UnityEditorInternal; -using UnityEngine; - -namespace VisualStudioEditor -{ - public interface IGenerator { - bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles); - void Sync(); - bool HasSolutionBeenGenerated(); - string SolutionFile(); - string ProjectDirectory { get; } - void GenerateAll(bool generateAll); - } - - public interface IAssemblyNameProvider - { - string GetAssemblyNameFromScriptPath(string path); - IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution); - IEnumerable GetAllAssetPaths(); - UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath); - } - - public struct TestSettings { - public bool ShouldSync; - public Dictionary SyncPath; - } - - class AssemblyNameProvider : IAssemblyNameProvider - { - public string GetAssemblyNameFromScriptPath(string path) - { - return CompilationPipeline.GetAssemblyNameFromScriptPath(path); - } - - public IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution) - { - return CompilationPipeline.GetAssemblies().Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution)); - } - - public IEnumerable GetAllAssetPaths() - { - return AssetDatabase.GetAllAssetPaths(); - } - - public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath) - { - return UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath); - } - } - - public class ProjectGeneration : IGenerator - { - enum ScriptingLanguage - { - None, - CSharp - } - - public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003"; - - const string k_WindowsNewline = "\r\n"; - - /// - /// Map source extensions to ScriptingLanguages - /// - static readonly Dictionary k_BuiltinSupportedExtensions = new Dictionary - { - { "cs", ScriptingLanguage.CSharp }, - { "uxml", ScriptingLanguage.None }, - { "uss", ScriptingLanguage.None }, - { "shader", ScriptingLanguage.None }, - { "compute", ScriptingLanguage.None }, - { "cginc", ScriptingLanguage.None }, - { "hlsl", ScriptingLanguage.None }, - { "glslinc", ScriptingLanguage.None } - }; - - string m_SolutionProjectEntryTemplate = string.Join("\r\n", - @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""", - @"EndProject").Replace(" ", "\t"); - - string m_SolutionProjectConfigurationTemplate = string.Join("\r\n", - @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", - @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU", - @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU", - @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t"); - - static readonly string[] k_ReimportSyncExtensions = { ".dll", ".asmdef" }; - - static readonly Regex k_ScriptReferenceExpression = new Regex( - @"^Library.ScriptAssemblies.(?(?.*)\.dll$)", - RegexOptions.Compiled | RegexOptions.IgnoreCase); - - string[] m_ProjectSupportedExtensions = new string[0]; - public string ProjectDirectory { get; } - - public TestSettings Settings { get; set; } - - readonly string m_ProjectName; - readonly IAssemblyNameProvider m_AssemblyNameProvider; - bool m_ShouldGenerateAll; - - public ProjectGeneration() : this(Directory.GetParent(Application.dataPath).FullName, new AssemblyNameProvider()) - { - } - - public ProjectGeneration(string tempDirectory) : this(tempDirectory, new AssemblyNameProvider()) { - } - - public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider) { - Settings = new TestSettings { ShouldSync = true }; - ProjectDirectory = tempDirectory.Replace('\\', '/'); - m_ProjectName = Path.GetFileName(ProjectDirectory); - m_AssemblyNameProvider = assemblyNameProvider; - } - - public void GenerateAll(bool generateAll) - { - m_ShouldGenerateAll = generateAll; - } - - /// - /// Syncs the scripting solution if any affected files are relevant. - /// - /// - /// Whether the solution was synced. - /// - /// - /// A set of files whose status has changed - /// - /// - /// A set of files that got reimported - /// - public bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles) - { - SetupProjectSupportedExtensions(); - - // Don't sync if we haven't synced before - if (HasSolutionBeenGenerated() && HasFilesBeenModified(affectedFiles, reimportedFiles)) - { - Sync(); - return true; - } - return false; - } - - bool HasFilesBeenModified(IEnumerable affectedFiles, IEnumerable reimportedFiles) - { - return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset); - } - - static bool ShouldSyncOnReimportedAsset(string asset) - { - return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension); - } - - public void Sync() - { - SetupProjectSupportedExtensions(); - bool externalCodeAlreadyGeneratedProjects = OnPreGeneratingCSProjectFiles(); - - if (!externalCodeAlreadyGeneratedProjects) - { - GenerateAndWriteSolutionAndProjects(); - } - OnGeneratedCSProjectFiles(); - } - - public bool HasSolutionBeenGenerated() - { - return File.Exists(SolutionFile()); - } - - void SetupProjectSupportedExtensions() - { - m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions; - } - - bool ShouldFileBePartOfSolution(string file) - { - string extension = Path.GetExtension(file); - - // Exclude files coming from packages except if they are internalized. - if (!m_ShouldGenerateAll && IsInternalizedPackagePath(file)) - { - return false; - } - - // Dll's are not scripts but still need to be included.. - if (extension == ".dll") - return true; - - if (file.ToLower().EndsWith(".asmdef")) - return true; - - return IsSupportedExtension(extension); - } - - bool IsSupportedExtension(string extension) - { - extension = extension.TrimStart('.'); - if (k_BuiltinSupportedExtensions.ContainsKey(extension)) - return true; - if (m_ProjectSupportedExtensions.Contains(extension)) - return true; - return false; - } - - static ScriptingLanguage ScriptingLanguageFor(Assembly island) - { - return ScriptingLanguageFor(GetExtensionOfSourceFiles(island.sourceFiles)); - } - - static string GetExtensionOfSourceFiles(string[] files) - { - return files.Length > 0 ? GetExtensionOfSourceFile(files[0]) : "NA"; - } - - static string GetExtensionOfSourceFile(string file) - { - var ext = Path.GetExtension(file).ToLower(); - ext = ext.Substring(1); //strip dot - return ext; - } - - static ScriptingLanguage ScriptingLanguageFor(string extension) - { - return k_BuiltinSupportedExtensions.TryGetValue(extension.TrimStart('.'), out var result) - ? result - : ScriptingLanguage.None; - } - - static List SafeGetTypes(System.Reflection.Assembly a) - { - var ret = new List(); - - try - { - ret = a.GetTypes().ToList(); - } - catch (System.Reflection.ReflectionTypeLoadException rtl) - { - ret = rtl.Types.ToList(); - } - catch (Exception) - { - return new List(); - } - - return ret.Where(r => r != null).ToList(); - } - - public void GenerateAndWriteSolutionAndProjects() - { - // Only synchronize islands that have associated source files and ones that we actually want in the project. - // This also filters out DLLs coming from .asmdef files in packages. - var assemblies = m_AssemblyNameProvider.GetAllAssemblies(ShouldFileBePartOfSolution); - - var allAssetProjectParts = GenerateAllAssetProjectParts(); - - var monoIslands = assemblies.ToList(); - - SyncSolution(monoIslands); - var allProjectIslands = RelevantIslandsForMode(monoIslands).ToList(); - foreach (Assembly assembly in allProjectIslands) - { - var responseFileData = ParseResponseFileData(assembly); - SyncProject(assembly, allAssetProjectParts, responseFileData, allProjectIslands); - } - } - - IEnumerable ParseResponseFileData(Assembly assembly) - { - var systemReferenceDirectories = CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel); - - Dictionary responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(x => x, x => CompilationPipeline.ParseResponseFile( - Path.Combine(ProjectDirectory, x), - ProjectDirectory, - systemReferenceDirectories - )); - - Dictionary responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any()) - .ToDictionary(x => x.Key, x => x.Value); - - if (responseFilesWithErrors.Any()) - { - foreach (var error in responseFilesWithErrors) - foreach (var valueError in error.Value.Errors) - { - Debug.LogError($"{error.Key} Parse Error : {valueError}"); - } - } - - return responseFilesData.Select(x => x.Value); - } - - Dictionary GenerateAllAssetProjectParts() - { - Dictionary stringBuilders = new Dictionary(); - - foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths()) - { - // Exclude files coming from packages except if they are internalized. - if (!m_ShouldGenerateAll && IsInternalizedPackagePath(asset)) - { - continue; - } - - string extension = Path.GetExtension(asset); - if (IsSupportedExtension(extension) && ScriptingLanguage.None == ScriptingLanguageFor(extension)) - { - // Find assembly the asset belongs to by adding script extension and using compilation pipeline. - var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset + ".cs"); - - if (string.IsNullOrEmpty(assemblyName)) - { - continue; - } - - assemblyName = Utility.FileNameWithoutExtension(assemblyName); - - if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder)) - { - projectBuilder = new StringBuilder(); - stringBuilders[assemblyName] = projectBuilder; - } - - projectBuilder.Append(" ").Append(k_WindowsNewline); - } - } - - var result = new Dictionary(); - - foreach (var entry in stringBuilders) - result[entry.Key] = entry.Value.ToString(); - - return result; - } - - bool IsInternalizedPackagePath(string file) - { - if (string.IsNullOrWhiteSpace(file)) - { - return false; - } - - var packageInfo = m_AssemblyNameProvider.FindForAssetPath(file); - if (packageInfo == null) { - return false; - } - var packageSource = packageInfo.source; - return packageSource != PackageSource.Embedded && packageSource != PackageSource.Local; - } - - void SyncProject( - Assembly island, - Dictionary allAssetsProjectParts, - IEnumerable responseFilesData, - List allProjectIslands) - { - SyncProjectFileIfNotChanged(ProjectFile(island), ProjectText(island, allAssetsProjectParts, responseFilesData, allProjectIslands)); - } - - void SyncProjectFileIfNotChanged(string path, string newContents) - { - if (Path.GetExtension(path) == ".csproj") - { - newContents = OnGeneratedCSProject(path, newContents); - } - - SyncFileIfNotChanged(path, newContents); - } - - void SyncSolutionFileIfNotChanged(string path, string newContents) - { - newContents = OnGeneratedSlnSolution(path, newContents); - - SyncFileIfNotChanged(path, newContents); - } - - static void OnGeneratedCSProjectFiles() - { - IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) - .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); - var args = new object[0]; - foreach (var type in types) - { - var method = type.GetMethod("OnGeneratedCSProjectFiles", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); - if (method == null) - { - continue; - } - method.Invoke(null, args); - } - } - - static bool OnPreGeneratingCSProjectFiles() - { - IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) - .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); - bool result = false; - foreach (var type in types) - { - var args = new object[0]; - var method = type.GetMethod("OnPreGeneratingCSProjectFiles", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); - if (method == null) - { - continue; - } - var returnValue = method.Invoke(null, args); - if (method.ReturnType == typeof(bool)) - { - result |= (bool)returnValue; - } - } - return result; - } - - static string OnGeneratedCSProject(string path, string content) - { - IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) - .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); - foreach (var type in types) - { - var args = new [] { path, content }; - var method = type.GetMethod("OnGeneratedCSProject", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); - if (method == null) - { - continue; - } - var returnValue = method.Invoke(null, args); - if (method.ReturnType == typeof(string)) - { - content = (string)returnValue; - } - } - return content; - } - - static string OnGeneratedSlnSolution(string path, string content) - { - IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) - .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); - foreach (var type in types) - { - var args = new [] { path, content }; - var method = type.GetMethod("OnGeneratedSlnSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); - if (method == null) - { - continue; - } - var returnValue = method.Invoke(null, args); - if (method.ReturnType == typeof(string)) - { - content = (string)returnValue; - } - } - return content; - } - - void SyncFileIfNotChanged(string filename, string newContents) - { - if (File.Exists(filename) && - newContents == File.ReadAllText(filename)) - { - return; - } - - if (Settings.ShouldSync) - { - File.WriteAllText(filename, newContents, Encoding.UTF8); - } - else - { - var utf8 = Encoding.UTF8; - byte[] utfBytes = utf8.GetBytes(newContents); - Settings.SyncPath[filename] = utf8.GetString(utfBytes, 0, utfBytes.Length); - } - } - - string ProjectText(Assembly assembly, - Dictionary allAssetsProjectParts, - IEnumerable responseFilesData, - List allProjectIslands) - { - var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData)); - var references = new List(); - var projectReferences = new List(); - - foreach (string file in assembly.sourceFiles) - { - if (!ShouldFileBePartOfSolution(file)) - continue; - - var extension = Path.GetExtension(file).ToLower(); - var fullFile = EscapedRelativePathFor(file); - if (".dll" != extension) - { - projectBuilder.Append(" ").Append(k_WindowsNewline); - } - else - { - references.Add(fullFile); - } - } - - var assemblyName = Utility.FileNameWithoutExtension(assembly.outputPath); - - // Append additional non-script files that should be included in project generation. - if (allAssetsProjectParts.TryGetValue(assemblyName, out var additionalAssetsForProject)) - projectBuilder.Append(additionalAssetsForProject); - - var islandRefs = references.Union(assembly.allReferences); - - foreach (string reference in islandRefs) - { - if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal) - || reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal) - || reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal) - || reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal)) - continue; - - var match = k_ScriptReferenceExpression.Match(reference); - if (match.Success) - { - // assume csharp language - // Add a reference to a project except if it's a reference to a script assembly - // that we are not generating a project for. This will be the case for assemblies - // coming from .assembly.json files in non-internalized packages. - var dllName = match.Groups["dllname"].Value; - if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName)) - { - projectReferences.Add(match); - continue; - } - } - - string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference); - - AppendReference(fullReference, projectBuilder); - } - - var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r)); - foreach (var reference in responseRefs) - { - AppendReference(reference, projectBuilder); - } - - if (0 < projectReferences.Count) - { - projectBuilder.AppendLine(" "); - projectBuilder.AppendLine(" "); - foreach (Match reference in projectReferences) - { - var referencedProject = reference.Groups["project"].Value; - - projectBuilder.Append(" ").Append(k_WindowsNewline); - projectBuilder.Append(" {").Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}").Append(k_WindowsNewline); - projectBuilder.Append(" ").Append(referencedProject).Append("").Append(k_WindowsNewline); - projectBuilder.AppendLine(" "); - } - } - - projectBuilder.Append(ProjectFooter()); - return projectBuilder.ToString(); - } - - static void AppendReference(string fullReference, StringBuilder projectBuilder) - { - //replace \ with / and \\ with / - var escapedFullPath = SecurityElement.Escape(fullReference); - escapedFullPath = escapedFullPath.Replace("\\", "/"); - escapedFullPath = escapedFullPath.Replace("\\\\", "/"); - projectBuilder.Append(" ").Append(k_WindowsNewline); - projectBuilder.Append(" ").Append(escapedFullPath).Append("").Append(k_WindowsNewline); - projectBuilder.Append(" ").Append(k_WindowsNewline); - } - - public string ProjectFile(Assembly assembly) - { - return Path.Combine(ProjectDirectory, $"{Utility.FileNameWithoutExtension(assembly.outputPath)}.csproj"); - } - - public string SolutionFile() - { - return Path.Combine(ProjectDirectory, $"{m_ProjectName}.sln"); - } - - string ProjectHeader( - Assembly island, - IEnumerable responseFilesData - ) - { - var toolsVersion = "4.0"; - var productVersion = "10.0.20506"; - const string baseDirectory = "."; - - var targetFrameworkVersion = "v4.7.1"; - var targetLanguageVersion = "latest"; - - var arguments = new object[] - { - toolsVersion, productVersion, ProjectGuid(island.outputPath), - InternalEditorUtility.GetEngineAssemblyPath(), - InternalEditorUtility.GetEditorAssemblyPath(), - string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(EditorUserBuildSettings.activeScriptCompilationDefines).Concat(island.defines).Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()), - MSBuildNamespaceUri, - Utility.FileNameWithoutExtension(island.outputPath), - EditorSettings.projectGenerationRootNamespace, - targetFrameworkVersion, - targetLanguageVersion, - baseDirectory, - island.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe) - }; - - try - { - return string.Format(GetProjectHeaderTemplate(), arguments); - } - catch (Exception) - { - throw new NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length); - } - } - - static string GetSolutionText() - { - return string.Join("\r\n", - @"", - @"Microsoft Visual Studio Solution File, Format Version {0}", - @"# Visual Studio {1}", - @"{2}", - @"Global", - @" GlobalSection(SolutionConfigurationPlatforms) = preSolution", - @" Debug|Any CPU = Debug|Any CPU", - @" Release|Any CPU = Release|Any CPU", - @" EndGlobalSection", - @" GlobalSection(ProjectConfigurationPlatforms) = postSolution", - @"{3}", - @" EndGlobalSection", - @" GlobalSection(SolutionProperties) = preSolution", - @" HideSolutionNode = FALSE", - @" EndGlobalSection", - @"EndGlobal", - @"").Replace(" ", "\t"); - } - - static string GetProjectFooterTemplate() - { - return string.Join("\r\n", - @" ", - @" ", - @" ", - @"", - @""); - } - - static string GetProjectHeaderTemplate() - { - var header = new[] - { - @"", - @"", - @" ", - @" {10}", - @" ", - @" ", - @" Debug", - @" AnyCPU", - @" {1}", - @" 2.0", - @" {8}", - @" {{{2}}}", - @" Library", - @" Properties", - @" {7}", - @" {9}", - @" 512", - @" {11}", - @" ", - @" ", - @" true", - @" full", - @" false", - @" Temp\bin\Debug\", - @" {5}", - @" prompt", - @" 4", - @" 0169", - @" {12}", - @" ", - @" ", - @" pdbonly", - @" true", - @" Temp\bin\Release\", - @" prompt", - @" 4", - @" 0169", - @" {12}", - @" " - }; - - var forceExplicitReferences = new[] - { - @" ", - @" true", - @" true", - @" false", - @" false", - @" false", - @" " - }; - - var itemGroupStart = new[] - { - @" " - }; - - var footer = new[] - { - @" ", - @" {3}", - @" ", - @" ", - @" {4}", - @" ", - @" ", - @" ", - @"" - }; - - var text = header.Concat(forceExplicitReferences).Concat(itemGroupStart).Concat(footer).ToArray(); - return string.Join("\r\n", text); - } - - void SyncSolution(IEnumerable islands) - { - SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(islands)); - } - - string SolutionText(IEnumerable islands) - { - var fileversion = "11.00"; - var vsversion = "2010"; - - var relevantIslands = RelevantIslandsForMode(islands); - string projectEntries = GetProjectEntries(relevantIslands); - string projectConfigurations = string.Join(k_WindowsNewline, relevantIslands.Select(i => GetProjectActiveConfigurations(ProjectGuid(i.outputPath))).ToArray()); - return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations); - } - - static IEnumerable RelevantIslandsForMode(IEnumerable islands) - { - IEnumerable relevantIslands = islands.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i)); - return relevantIslands; - } - - /// - /// Get a Project("{guid}") = "MyProject", "MyProject.unityproj", "{projectguid}" - /// entry for each relevant language - /// - string GetProjectEntries(IEnumerable islands) - { - var projectEntries = islands.Select(i => string.Format( - m_SolutionProjectEntryTemplate, - SolutionGuid(i), Utility.FileNameWithoutExtension(i.outputPath), Path.GetFileName(ProjectFile(i)), ProjectGuid(i.outputPath) - )); - - return string.Join(k_WindowsNewline, projectEntries.ToArray()); - } - - /// - /// Generate the active configuration string for a given project guid - /// - string GetProjectActiveConfigurations(string projectGuid) - { - return string.Format( - m_SolutionProjectConfigurationTemplate, - projectGuid); - } - - string EscapedRelativePathFor(string file) - { - var projectDir = ProjectDirectory.Replace('/', '\\'); - file = file.Replace('/', '\\'); - var path = SkipPathPrefix(file, projectDir); - - var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/')); - if (packageInfo != null) { - // We have to normalize the path, because the PackageManagerRemapper assumes - // dir seperators will be os specific. - var absolutePath = Path.GetFullPath(NormalizePath(path)).Replace('/', '\\'); - path = SkipPathPrefix(absolutePath, projectDir); - } - - return SecurityElement.Escape(path); - } - - static string SkipPathPrefix(string path, string prefix) - { - if (path.Replace("\\","/").StartsWith($"{prefix}/")) - return path.Substring(prefix.Length + 1); - return path; - } - - static string NormalizePath(string path) - { - if (Path.DirectorySeparatorChar == '\\') - return path.Replace('/', Path.DirectorySeparatorChar); - return path.Replace('\\', Path.DirectorySeparatorChar); - } - - - string ProjectGuid(string assembly) - { - return SolutionGuidGenerator.GuidForProject(m_ProjectName + Utility.FileNameWithoutExtension(assembly)); - } - - string SolutionGuid(Assembly island) - { - return SolutionGuidGenerator.GuidForSolution(m_ProjectName, GetExtensionOfSourceFiles(island.sourceFiles)); - } - - static string ProjectFooter() - { - return GetProjectFooterTemplate(); - } - - static string GetProjectExtension() - { - return ".csproj"; - } - } - - public static class SolutionGuidGenerator - { - public static string GuidForProject(string projectName) - { - return ComputeGuidHashFor(projectName + "salt"); - } - - public static string GuidForSolution(string projectName, string sourceFileExtension) - { - if (sourceFileExtension.ToLower() == "cs") - // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs - return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"; - - return ComputeGuidHashFor(projectName); - } - - static string ComputeGuidHashFor(string input) - { - var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input)); - return HashAsGuid(HashToString(hash)); - } - - static string HashAsGuid(string hash) - { - var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" + hash.Substring(16, 4) + "-" + hash.Substring(20, 12); - return guid.ToUpper(); - } - - static string HashToString(byte[] bs) - { - var sb = new StringBuilder(); - foreach (byte b in bs) - sb.Append(b.ToString("x2")); - return sb.ToString(); - } - } -} +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Unity Technologies. + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using Unity.CodeEditor; +using UnityEditor; +using UnityEditor.Compilation; +using UnityEditor.PackageManager; +using UnityEditorInternal; +using UnityEngine; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + public enum ScriptingLanguage + { + None, + CSharp + } + + public interface IGenerator { + bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles); + void Sync(); + bool HasSolutionBeenGenerated(); + string SolutionFile(); + string ProjectDirectory { get; } + void GenerateAll(bool generateAll); + bool IsSupportedFile(string path); + } + + public interface IAssemblyNameProvider + { + string GetAssemblyNameFromScriptPath(string path); + IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution); + IEnumerable GetAllAssetPaths(); + UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath); + } + + public struct TestSettings { + public bool ShouldSync; + public Dictionary SyncPath; + } + + class AssemblyNameProvider : IAssemblyNameProvider + { + public string GetAssemblyNameFromScriptPath(string path) + { + return CompilationPipeline.GetAssemblyNameFromScriptPath(path); + } + + public IEnumerable GetAllAssemblies(Func shouldFileBePartOfSolution) + { + return CompilationPipeline.GetAssemblies().Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution)); + } + + public IEnumerable GetAllAssetPaths() + { + return AssetDatabase.GetAllAssetPaths(); + } + + public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath) + { + return UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath); + } + } + + public class ProjectGeneration : IGenerator + { + public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003"; + + const string k_WindowsNewline = "\r\n"; + + string m_SolutionProjectEntryTemplate = string.Join("\r\n", + @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""", + @"EndProject").Replace(" ", "\t"); + + string m_SolutionProjectConfigurationTemplate = string.Join("\r\n", + @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", + @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU", + @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU", + @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t"); + + static readonly string[] k_ReimportSyncExtensions = { ".dll", ".asmdef" }; + + static readonly Regex k_ScriptReferenceExpression = new Regex( + @"^Library.ScriptAssemblies.(?(?.*)\.dll$)", + RegexOptions.Compiled | RegexOptions.IgnoreCase); + + string[] m_ProjectSupportedExtensions = new string[0]; + string[] m_BuiltinSupportedExtensions = new string[0]; + + public string ProjectDirectory { get; } + + public TestSettings Settings { get; set; } + + readonly string m_ProjectName; + readonly IAssemblyNameProvider m_AssemblyNameProvider; + bool m_ShouldGenerateAll; + + public ProjectGeneration() : this(Directory.GetParent(Application.dataPath).FullName, new AssemblyNameProvider()) + { + } + + public ProjectGeneration(string tempDirectory) : this(tempDirectory, new AssemblyNameProvider()) { + } + + public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider) { + Settings = new TestSettings { ShouldSync = true }; + ProjectDirectory = tempDirectory.Replace('\\', '/'); + m_ProjectName = Path.GetFileName(ProjectDirectory); + m_AssemblyNameProvider = assemblyNameProvider; + + SetupProjectSupportedExtensions(); + } + + public void GenerateAll(bool generateAll) + { + m_ShouldGenerateAll = generateAll; + } + + /// + /// Syncs the scripting solution if any affected files are relevant. + /// + /// + /// Whether the solution was synced. + /// + /// + /// A set of files whose status has changed + /// + /// + /// A set of files that got reimported + /// + public bool SyncIfNeeded(IEnumerable affectedFiles, IEnumerable reimportedFiles) + { + SetupProjectSupportedExtensions(); + + // Don't sync if we haven't synced before + if (HasSolutionBeenGenerated() && HasFilesBeenModified(affectedFiles, reimportedFiles)) + { + Sync(); + return true; + } + return false; + } + + bool HasFilesBeenModified(IEnumerable affectedFiles, IEnumerable reimportedFiles) + { + return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset); + } + + static bool ShouldSyncOnReimportedAsset(string asset) + { + return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension); + } + + public void Sync() + { + SetupProjectSupportedExtensions(); + bool externalCodeAlreadyGeneratedProjects = OnPreGeneratingCSProjectFiles(); + + if (!externalCodeAlreadyGeneratedProjects) + { + GenerateAndWriteSolutionAndProjects(); + } + OnGeneratedCSProjectFiles(); + } + + public bool HasSolutionBeenGenerated() + { + return File.Exists(SolutionFile()); + } + + void SetupProjectSupportedExtensions() + { + m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions; + m_BuiltinSupportedExtensions = EditorSettings.projectGenerationBuiltinExtensions; + } + + bool ShouldFileBePartOfSolution(string file) + { + // Exclude files coming from packages except if they are internalized. + if (!m_ShouldGenerateAll && IsInternalizedPackagePath(file)) + { + return false; + } + + return IsSupportedFile(file); + } + + static string GetExtensionWithoutDot(string path) + { + // Prevent re-processing and information loss + if (!Path.HasExtension(path)) + return path; + + return Path + .GetExtension(path) + .TrimStart('.') + .ToLower(); + } + + public bool IsSupportedFile(string path) + { + var extension = GetExtensionWithoutDot(path); + + // Dll's are not scripts but still need to be included + if (extension == "dll") + return true; + + if (extension == "asmdef") + return true; + + if (m_BuiltinSupportedExtensions.Contains(extension)) + return true; + + if (m_ProjectSupportedExtensions.Contains(extension)) + return true; + + return false; + } + + static ScriptingLanguage ScriptingLanguageFor(Assembly island) + { + var files = island.sourceFiles; + + if (files.Length == 0) + return ScriptingLanguage.None; + + return ScriptingLanguageFor(files[0]); + } + + static ScriptingLanguage ScriptingLanguageFor(string path) + { + return GetExtensionWithoutDot(path) == "cs" ? ScriptingLanguage.CSharp : ScriptingLanguage.None; + } + + static List SafeGetTypes(System.Reflection.Assembly a) + { + var ret = new List(); + + try + { + ret = a.GetTypes().ToList(); + } + catch (System.Reflection.ReflectionTypeLoadException rtl) + { + ret = rtl.Types.ToList(); + } + catch (Exception) + { + return new List(); + } + + return ret.Where(r => r != null).ToList(); + } + + public void GenerateAndWriteSolutionAndProjects() + { + // Only synchronize islands that have associated source files and ones that we actually want in the project. + // This also filters out DLLs coming from .asmdef files in packages. + var assemblies = m_AssemblyNameProvider.GetAllAssemblies(ShouldFileBePartOfSolution); + + var allAssetProjectParts = GenerateAllAssetProjectParts(); + + var monoIslands = assemblies.ToList(); + + SyncSolution(monoIslands); + var allProjectIslands = RelevantIslandsForMode(monoIslands).ToList(); + foreach (Assembly assembly in allProjectIslands) + { + var responseFileData = ParseResponseFileData(assembly); + SyncProject(assembly, allAssetProjectParts, responseFileData, allProjectIslands); + } + } + + IEnumerable ParseResponseFileData(Assembly assembly) + { + var systemReferenceDirectories = CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel); + + Dictionary responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(x => x, x => CompilationPipeline.ParseResponseFile( + Path.Combine(ProjectDirectory, x), + ProjectDirectory, + systemReferenceDirectories + )); + + Dictionary responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any()) + .ToDictionary(x => x.Key, x => x.Value); + + if (responseFilesWithErrors.Any()) + { + foreach (var error in responseFilesWithErrors) + foreach (var valueError in error.Value.Errors) + { + Debug.LogError($"{error.Key} Parse Error : {valueError}"); + } + } + + return responseFilesData.Select(x => x.Value); + } + + Dictionary GenerateAllAssetProjectParts() + { + Dictionary stringBuilders = new Dictionary(); + + foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths()) + { + // Exclude files coming from packages except if they are internalized. + if (!m_ShouldGenerateAll && IsInternalizedPackagePath(asset)) + { + continue; + } + + if (IsSupportedFile(asset) && ScriptingLanguage.None == ScriptingLanguageFor(asset)) + { + // Find assembly the asset belongs to by adding script extension and using compilation pipeline. + var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset + ".cs"); + + if (string.IsNullOrEmpty(assemblyName)) + { + continue; + } + + assemblyName = FileUtility.FileNameWithoutExtension(assemblyName); + + if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder)) + { + projectBuilder = new StringBuilder(); + stringBuilders[assemblyName] = projectBuilder; + } + + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + } + + var result = new Dictionary(); + + foreach (var entry in stringBuilders) + result[entry.Key] = entry.Value.ToString(); + + return result; + } + + bool IsInternalizedPackagePath(string file) + { + if (string.IsNullOrWhiteSpace(file)) + { + return false; + } + + var packageInfo = m_AssemblyNameProvider.FindForAssetPath(file); + if (packageInfo == null) { + return false; + } + var packageSource = packageInfo.source; + return packageSource != PackageSource.Embedded && packageSource != PackageSource.Local; + } + + void SyncProject( + Assembly island, + Dictionary allAssetsProjectParts, + IEnumerable responseFilesData, + List allProjectIslands) + { + SyncProjectFileIfNotChanged(ProjectFile(island), ProjectText(island, allAssetsProjectParts, responseFilesData, allProjectIslands)); + } + + void SyncProjectFileIfNotChanged(string path, string newContents) + { + if (Path.GetExtension(path) == ".csproj") + { + newContents = OnGeneratedCSProject(path, newContents); + } + + SyncFileIfNotChanged(path, newContents); + } + + void SyncSolutionFileIfNotChanged(string path, string newContents) + { + newContents = OnGeneratedSlnSolution(path, newContents); + + SyncFileIfNotChanged(path, newContents); + } + + static void OnGeneratedCSProjectFiles() + { + IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) + .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); + var args = new object[0]; + foreach (var type in types) + { + var method = type.GetMethod("OnGeneratedCSProjectFiles", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + method.Invoke(null, args); + } + } + + static bool OnPreGeneratingCSProjectFiles() + { + IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) + .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); + bool result = false; + foreach (var type in types) + { + var args = new object[0]; + var method = type.GetMethod("OnPreGeneratingCSProjectFiles", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + var returnValue = method.Invoke(null, args); + if (method.ReturnType == typeof(bool)) + { + result |= (bool)returnValue; + } + } + return result; + } + + static string OnGeneratedCSProject(string path, string content) + { + IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) + .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); + foreach (var type in types) + { + var args = new [] { path, content }; + var method = type.GetMethod("OnGeneratedCSProject", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + var returnValue = method.Invoke(null, args); + if (method.ReturnType == typeof(string)) + { + content = (string)returnValue; + } + } + return content; + } + + static string OnGeneratedSlnSolution(string path, string content) + { + IEnumerable types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => SafeGetTypes(x)) + .Where(x => typeof(AssetPostprocessor).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); + foreach (var type in types) + { + var args = new [] { path, content }; + var method = type.GetMethod("OnGeneratedSlnSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); + if (method == null) + { + continue; + } + var returnValue = method.Invoke(null, args); + if (method.ReturnType == typeof(string)) + { + content = (string)returnValue; + } + } + return content; + } + + void SyncFileIfNotChanged(string filename, string newContents) + { + if (File.Exists(filename) && + newContents == File.ReadAllText(filename)) + { + return; + } + + if (Settings.ShouldSync) + { + File.WriteAllText(filename, newContents, Encoding.UTF8); + } + else + { + var utf8 = Encoding.UTF8; + byte[] utfBytes = utf8.GetBytes(newContents); + Settings.SyncPath[filename] = utf8.GetString(utfBytes, 0, utfBytes.Length); + } + } + + string ProjectText(Assembly assembly, + Dictionary allAssetsProjectParts, + IEnumerable responseFilesData, + List allProjectIslands) + { + var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData)); + var references = new List(); + var projectReferences = new List(); + + projectBuilder.Append(@" ").Append(k_WindowsNewline); + foreach (string file in assembly.sourceFiles) + { + if (!ShouldFileBePartOfSolution(file)) + continue; + + var extension = Path.GetExtension(file).ToLower(); + var fullFile = EscapedRelativePathFor(file); + if (".dll" != extension) + { + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + else + { + references.Add(fullFile); + } + } + projectBuilder.Append(@" ").Append(k_WindowsNewline); + + var assemblyName = FileUtility.FileNameWithoutExtension(assembly.outputPath); + + projectBuilder.Append(@" ").Append(k_WindowsNewline); + // Append additional non-script files that should be included in project generation. + if (allAssetsProjectParts.TryGetValue(assemblyName, out var additionalAssetsForProject)) + projectBuilder.Append(additionalAssetsForProject); + + var islandRefs = references.Union(assembly.allReferences); + + foreach (string reference in islandRefs) + { + if (reference.EndsWith("/UnityEditor.dll", StringComparison.Ordinal) + || reference.EndsWith("/UnityEngine.dll", StringComparison.Ordinal) + || reference.EndsWith("\\UnityEditor.dll", StringComparison.Ordinal) + || reference.EndsWith("\\UnityEngine.dll", StringComparison.Ordinal)) + continue; + + var match = k_ScriptReferenceExpression.Match(reference); + if (match.Success) + { + // assume csharp language + // Add a reference to a project except if it's a reference to a script assembly + // that we are not generating a project for. This will be the case for assemblies + // coming from .assembly.json files in non-internalized packages. + var dllName = match.Groups["dllname"].Value; + if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName)) + { + projectReferences.Add(match); + continue; + } + } + + string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference); + + AppendReference(fullReference, projectBuilder); + } + + var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r)); + foreach (var reference in responseRefs) + { + AppendReference(reference, projectBuilder); + } + projectBuilder.Append(@" ").Append(k_WindowsNewline); + + if (0 < projectReferences.Count) + { + projectBuilder.Append(@" ").Append(k_WindowsNewline); + foreach (Match reference in projectReferences) + { + var referencedProject = reference.Groups["project"].Value; + + projectBuilder.Append(" ").Append(k_WindowsNewline); + projectBuilder.Append(" {").Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(referencedProject).Append("").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + projectBuilder.Append(@" ").Append(k_WindowsNewline); + } + + projectBuilder.Append(ProjectFooter()); + return projectBuilder.ToString(); + } + + static string XmlFilename(string path) + { + if (string.IsNullOrEmpty(path)) + return path; + + path = path.Replace(@"%", "%25"); + path = path.Replace(@";", "%3b"); + + return XmlEscape(path); + } + + static string XmlEscape(string s) + { + return SecurityElement.Escape(s); + } + + void AppendReference(string fullReference, StringBuilder projectBuilder) + { + var escapedFullPath = EscapedRelativePathFor(fullReference); + projectBuilder.Append(" ").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(escapedFullPath).Append("").Append(k_WindowsNewline); + projectBuilder.Append(" ").Append(k_WindowsNewline); + } + + public string ProjectFile(Assembly assembly) + { + return Path.Combine(ProjectDirectory, $"{FileUtility.FileNameWithoutExtension(assembly.outputPath)}.csproj"); + } + + private static readonly Regex InvalidCharactersRegexPattern = new Regex(@"\?|&|\*|""|<|>|\||#|%|\^|;" + (VisualStudioEditor.IsWindows ? "" : "|:")); + public string SolutionFile() + { + return Path.Combine(FileUtility.Normalize(ProjectDirectory), $"{InvalidCharactersRegexPattern.Replace(m_ProjectName,"_")}.sln"); + } + + string ProjectHeader( + Assembly island, + IEnumerable responseFilesData + ) + { + var toolsVersion = "4.0"; + var productVersion = "10.0.20506"; + const string baseDirectory = "."; + + var targetFrameworkVersion = "v4.7.1"; + var targetLanguageVersion = "latest"; + + var projectType = ProjectTypeOf(island.outputPath); + + var arguments = new object[] + { + toolsVersion, productVersion, ProjectGuid(island.outputPath), + XmlFilename(FileUtility.Normalize(InternalEditorUtility.GetEngineAssemblyPath())), + XmlFilename(FileUtility.Normalize(InternalEditorUtility.GetEditorAssemblyPath())), + string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(EditorUserBuildSettings.activeScriptCompilationDefines).Concat(island.defines).Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()), + MSBuildNamespaceUri, + FileUtility.FileNameWithoutExtension(island.outputPath), + EditorSettings.projectGenerationRootNamespace, + targetFrameworkVersion, + targetLanguageVersion, + baseDirectory, + island.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe), + // flavoring + projectType + ":" + (int)projectType, + EditorUserBuildSettings.activeBuildTarget + ":" + (int)EditorUserBuildSettings.activeBuildTarget, + Application.unityVersion, + }; + + try + { + return string.Format(GetProjectHeaderTemplate(), arguments); + } + catch (Exception) + { + throw new NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length); + } + } + + private enum ProjectType + { + GamePlugins = 3, + Game = 1, + EditorPlugins = 7, + Editor = 5, + } + + private static ProjectType ProjectTypeOf(string fileName) + { + var plugins = fileName.Contains("firstpass"); + var editor = fileName.Contains("Editor"); + + if (plugins && editor) + return ProjectType.EditorPlugins; + if (plugins) + return ProjectType.GamePlugins; + if (editor) + return ProjectType.Editor; + + return ProjectType.Game; + } + + static string GetSolutionText() + { + return string.Join("\r\n", + @"", + @"Microsoft Visual Studio Solution File, Format Version {0}", + @"# Visual Studio {1}", + @"{2}", + @"Global", + @" GlobalSection(SolutionConfigurationPlatforms) = preSolution", + @" Debug|Any CPU = Debug|Any CPU", + @" Release|Any CPU = Release|Any CPU", + @" EndGlobalSection", + @" GlobalSection(ProjectConfigurationPlatforms) = postSolution", + @"{3}", + @" EndGlobalSection", + @"{4}", + @"EndGlobal", + @"").Replace(" ", "\t"); + } + + static string GetProjectFooterTemplate() + { + return string.Join("\r\n", + @" ", + @" ", + @" ", + @"", + @""); + } + + string GetProjectHeaderTemplate() + { + var header = new[] + { + @"", + @"", + @" ", + @" {10}", + @" ", + @" ", + @" Debug", + @" AnyCPU", + @" {1}", + @" 2.0", + @" {8}", + @" {{{2}}}", + @" Library", + @" Properties", + @" {7}", + @" {9}", + @" 512", + @" {11}", + @" ", + @" ", + @" true", + @" full", + @" false", + @" Temp\bin\Debug\", + @" {5}", + @" prompt", + @" 4", + @" 0169", + @" {12}", + @" ", + @" ", + @" pdbonly", + @" true", + @" Temp\bin\Release\", + @" prompt", + @" 4", + @" 0169", + @" {12}", + @" " + }; + + var forceExplicitReferences = new[] + { + @" ", + @" true", + @" true", + @" false", + @" false", + @" false", + @" " + }; + + var flavoring = new[] + { + @" ", + @" {{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}};{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}", + @" Package", + @" {13}", + @" {14}", + @" {15}", + @" " + }; + + var footer = new[] + { + @" ", + @" ", + @" {3}", + @" ", + @" ", + @" {4}", + @" ", + @" ", + @"" + }; + + var lines = header + .Concat(forceExplicitReferences) + .Concat(flavoring) + .ToList(); + + // Only add analyzer block for compatible Visual Studio + if (CodeEditor.CurrentEditor is VisualStudioEditor editor && editor.TryGetVisualStudioInstallationForPath(CodeEditor.CurrentEditorInstallation, out var installation)) + { + if (installation.SupportsAnalyzers) + { + var analyzers = installation.GetAnalyzers(); + if (analyzers != null && analyzers.Length > 0) + { + lines.Add(@" "); + foreach (var analyzer in analyzers) + lines.Add(string.Format(@" ", EscapedRelativePathFor(analyzer))); + lines.Add(@" "); + } + } + } + + return string.Join("\r\n", lines + .Concat(footer)); + } + + void SyncSolution(IEnumerable islands) + { + if (InvalidCharactersRegexPattern.IsMatch(ProjectDirectory)) + Debug.LogWarning("Project path contains special characters, which can be an issue when opening Visual Studio"); + + var solutionFile = SolutionFile(); + var previousSolution = File.Exists(solutionFile) ? SolutionParser.ParseSolutionFile(solutionFile) : null; + SyncSolutionFileIfNotChanged(solutionFile, SolutionText(islands, previousSolution)); + } + + string SolutionText(IEnumerable islands, Solution previousSolution = null) + { + const string fileversion = "12.00"; + const string vsversion = "15"; + + var relevantIslands = RelevantIslandsForMode(islands); + var generatedProjects = ToProjectEntries(relevantIslands); + + SolutionProperties[] properties = null; + + // First, add all projects generated by Unity to the solution + var projects = new List(); + projects.AddRange(generatedProjects); + + if (previousSolution != null) + { + // Add all projects that were previously in the solution and that are not generated by Unity, nor generated in the project root directory + var externalProjects = previousSolution.Projects + .Where(p => !FileUtility.IsFileInProjectDirectory(p.FileName)) + .Where(p => generatedProjects.All(gp => gp.FileName != p.FileName)); + + projects.AddRange(externalProjects); + properties = previousSolution.Properties; + } + + string propertiesText = GetPropertiesText(properties); + string projectEntriesText = GetProjectEntriesText(projects); + string projectConfigurationsText = string.Join(k_WindowsNewline, projects.Select(p => GetProjectActiveConfigurations(p.ProjectGuid)).ToArray()); + return string.Format(GetSolutionText(), fileversion, vsversion, projectEntriesText, projectConfigurationsText, propertiesText); + } + + static IEnumerable RelevantIslandsForMode(IEnumerable islands) + { + IEnumerable relevantIslands = islands.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i)); + return relevantIslands; + } + + private string GetPropertiesText(SolutionProperties[] array) + { + if (array == null || array.Length == 0) + { + // HideSolution by default + array = new SolutionProperties[] { + new SolutionProperties() { + Name = "SolutionProperties", + Type = "preSolution", + Entries = new List>() { new KeyValuePair ("HideSolutionNode", "FALSE") } + } + }; + } + var result = new StringBuilder(); + + for (var i = 0; i 0) + result.Append(k_WindowsNewline); + + var properties = array[i]; + + result.Append($"\tGlobalSection({properties.Name}) = {properties.Type}"); + result.Append(k_WindowsNewline); + + foreach (var entry in properties.Entries) + { + result.Append($"\t\t{entry.Key} = {entry.Value}"); + result.Append(k_WindowsNewline); + } + + result.Append("\tEndGlobalSection"); + } + + return result.ToString(); + } + + /// + /// Get a Project("{guid}") = "MyProject", "MyProject.unityproj", "{projectguid}" + /// entry for each relevant language + /// + string GetProjectEntriesText(IEnumerable entries) + { + var projectEntries = entries.Select(entry => string.Format( + m_SolutionProjectEntryTemplate, + entry.ProjectFactoryGuid, entry.Name, entry.FileName, entry.ProjectGuid + )); + + return string.Join(k_WindowsNewline, projectEntries.ToArray()); + } + + IEnumerable ToProjectEntries(IEnumerable islands) + { + foreach (var island in islands) + yield return new SolutionProjectEntry() + { + ProjectFactoryGuid = SolutionGuid(island), + Name = FileUtility.FileNameWithoutExtension(island.outputPath), + FileName = Path.GetFileName(ProjectFile(island)), + ProjectGuid = ProjectGuid(island.outputPath) + }; + } + + /// + /// Generate the active configuration string for a given project guid + /// + string GetProjectActiveConfigurations(string projectGuid) + { + return string.Format( + m_SolutionProjectConfigurationTemplate, + projectGuid); + } + + string EscapedRelativePathFor(string file) + { + var projectDir = FileUtility.Normalize(ProjectDirectory); + file = FileUtility.Normalize(file); + var path = SkipPathPrefix(file, projectDir); + + var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/')); + if (packageInfo != null) { + // We have to normalize the path, because the PackageManagerRemapper assumes + // dir seperators will be os specific. + var absolutePath = Path.GetFullPath(FileUtility.Normalize(path)); + path = SkipPathPrefix(absolutePath, projectDir); + } + + return XmlFilename(path); + } + + static string SkipPathPrefix(string path, string prefix) + { + if (path.StartsWith($"{prefix}{Path.DirectorySeparatorChar}") && (path.Length > prefix.Length)) + return path.Substring(prefix.Length + 1); + return path; + } + + string ProjectGuid(string assembly) + { + return SolutionGuidGenerator.GuidForProject(m_ProjectName + FileUtility.FileNameWithoutExtension(assembly)); + } + + string SolutionGuid(Assembly island) + { + return SolutionGuidGenerator.GuidForSolution(m_ProjectName, ScriptingLanguageFor(island)); + } + + static string ProjectFooter() + { + return GetProjectFooterTemplate(); + } + + static string GetProjectExtension() + { + return ".csproj"; + } + } + + public static class SolutionGuidGenerator + { + public static string GuidForProject(string projectName) + { + return ComputeGuidHashFor(projectName + "salt"); + } + + public static string GuidForSolution(string projectName, ScriptingLanguage language) + { + if (language == ScriptingLanguage.CSharp) + { + // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs + return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"; + } + + return ComputeGuidHashFor(projectName); + } + + static string ComputeGuidHashFor(string input) + { + var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input)); + return HashAsGuid(HashToString(hash)); + } + + static string HashAsGuid(string hash) + { + var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" + hash.Substring(16, 4) + "-" + hash.Substring(20, 12); + return guid.ToUpper(); + } + + static string HashToString(byte[] bs) + { + var sb = new StringBuilder(); + foreach (byte b in bs) + sb.Append(b.ToString("x2")); + return sb.ToString(); + } + } +} diff --git a/Editor/ProjectGeneration.cs.meta b/Editor/ProjectGeneration.cs.meta index c5153ae..645df67 100644 --- a/Editor/ProjectGeneration.cs.meta +++ b/Editor/ProjectGeneration.cs.meta @@ -1,11 +1,11 @@ -fileFormatVersion: 2 -guid: c55bbb5ab4b342946980281be9e63c1a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: c55bbb5ab4b342946980281be9e63c1a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Solution.cs b/Editor/Solution.cs new file mode 100644 index 0000000..1db7ed2 --- /dev/null +++ b/Editor/Solution.cs @@ -0,0 +1,12 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal class Solution + { + public SolutionProjectEntry[] Projects { get; set; } + public SolutionProperties[] Properties { get; set; } + } +} diff --git a/Editor/Solution.cs.meta b/Editor/Solution.cs.meta new file mode 100644 index 0000000..6e88569 --- /dev/null +++ b/Editor/Solution.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: af4c2c762e1d8e949a6bc458973df6e7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/SolutionParser.cs b/Editor/SolutionParser.cs new file mode 100644 index 0000000..ff5aa00 --- /dev/null +++ b/Editor/SolutionParser.cs @@ -0,0 +1,80 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal static class SolutionParser + { + // Compared to the bridge implementation, we are not returning "{" "}" from Guids + private static readonly Regex ProjectDeclaration = new Regex(@"Project\(\""{(?.*?)}\""\)\s+=\s+\""(?.*?)\"",\s+\""(?.*?)\"",\s+\""{(?.*?)}\""(?.*?)\bEndProject\b", RegexOptions.Singleline | RegexOptions.ExplicitCapture); + private static readonly Regex PropertiesDeclaration = new Regex(@"GlobalSection\((?[\w]+Properties)\)\s+=\s+(?(?:post|pre)Solution)(?.*?)EndGlobalSection", RegexOptions.Singleline | RegexOptions.ExplicitCapture); + private static readonly Regex PropertiesEntryDeclaration = new Regex(@"^\s*(?.*?)=(?.*?)$", RegexOptions.Multiline | RegexOptions.ExplicitCapture); + + public static Solution ParseSolutionFile(string filename) + { + return ParseSolutionContent(File.ReadAllText(filename)); + } + + public static Solution ParseSolutionContent(string content) + { + return new Solution + { + Projects = ParseSolutionProjects(content), + Properties = ParseSolutionProperties(content) + }; + } + + private static SolutionProjectEntry[] ParseSolutionProjects(string content) + { + var projects = new List(); + var mc = ProjectDeclaration.Matches(content); + + foreach (Match match in mc) + { + projects.Add(new SolutionProjectEntry + { + ProjectFactoryGuid = match.Groups["projectFactoryGuid"].Value, + Name = match.Groups["name"].Value, + FileName = match.Groups["fileName"].Value, + ProjectGuid = match.Groups["projectGuid"].Value, + }); + } + + return projects.ToArray(); + } + + private static SolutionProperties[] ParseSolutionProperties(string content) + { + var properties = new List(); + var mc = PropertiesDeclaration.Matches(content); + + foreach (Match match in mc) + { + var sp = new SolutionProperties + { + Entries = new List>(), + Name = match.Groups["name"].Value, + Type = match.Groups["type"].Value + }; + + var entries = match.Groups["entries"].Value; + var mec = PropertiesEntryDeclaration.Matches(entries); + foreach (Match entry in mec) + { + var key = entry.Groups["key"].Value.Trim(); + var value = entry.Groups["value"].Value.Trim(); + sp.Entries.Add(new KeyValuePair(key, value)); + } + + properties.Add(sp); + } + + return properties.ToArray(); + } + } +} diff --git a/Editor/SolutionParser.cs.meta b/Editor/SolutionParser.cs.meta new file mode 100644 index 0000000..208d8a8 --- /dev/null +++ b/Editor/SolutionParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fbbb1ee655846b043baf6c3502b5ce49 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/SolutionProjectEntry.cs b/Editor/SolutionProjectEntry.cs new file mode 100644 index 0000000..4319b94 --- /dev/null +++ b/Editor/SolutionProjectEntry.cs @@ -0,0 +1,14 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal class SolutionProjectEntry + { + public string ProjectFactoryGuid { get; set; } + public string Name { get; set; } + public string FileName { get; set; } + public string ProjectGuid { get; set; } + } +} diff --git a/Editor/SolutionProjectEntry.cs.meta b/Editor/SolutionProjectEntry.cs.meta new file mode 100644 index 0000000..c125a32 --- /dev/null +++ b/Editor/SolutionProjectEntry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5c1b8a755d2c97640bbb207c43f4cf61 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/SolutionProperties.cs b/Editor/SolutionProperties.cs new file mode 100644 index 0000000..c0cf791 --- /dev/null +++ b/Editor/SolutionProperties.cs @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections.Generic; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal class SolutionProperties + { + public string Name { get; set; } + public IList> Entries { get; set; } + public string Type { get; set; } + } +} diff --git a/Editor/SolutionProperties.cs.meta b/Editor/SolutionProperties.cs.meta new file mode 100644 index 0000000..b4eedd1 --- /dev/null +++ b/Editor/SolutionProperties.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 829d4d6bc39fd1044ba4c5fc2a9c911f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Symbols.cs b/Editor/Symbols.cs new file mode 100644 index 0000000..076fec6 --- /dev/null +++ b/Editor/Symbols.cs @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal static class Symbols + { + public static bool IsPortableSymbolFile(string pdbFile) + { + try + { + using (var stream = File.OpenRead(pdbFile)) + { + return stream.ReadByte() == 'B' + && stream.ReadByte() == 'S' + && stream.ReadByte() == 'J' + && stream.ReadByte() == 'B'; + } + } + catch (Exception) + { + return false; + } + } + } +} diff --git a/Editor/Symbols.cs.meta b/Editor/Symbols.cs.meta new file mode 100644 index 0000000..0923a63 --- /dev/null +++ b/Editor/Symbols.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b9308b762484008498bb5cd1886aa491 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/Utility.cs b/Editor/Utility.cs deleted file mode 100644 index 2e773b2..0000000 --- a/Editor/Utility.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace VisualStudioEditor -{ - public static class Utility - { - public static string FileNameWithoutExtension(string path) - { - if (string.IsNullOrEmpty(path)) - { - return ""; - } - - var indexOfDot = -1; - var indexOfSlash = 0; - for (var i = path.Length - 1; i >= 0; i--) - { - if (indexOfDot == -1 && path[i] == '.') - { - indexOfDot = i; - } - if (indexOfSlash == 0 && path[i] == '/' || path[i] == '\\') - { - indexOfSlash = i + 1; - break; - } - } - - if (indexOfDot == -1) - { - indexOfDot = path.Length - 1; - } - - return path.Substring(indexOfSlash, indexOfDot - indexOfSlash); - } - } -} \ No newline at end of file diff --git a/Editor/VSEditor.cs b/Editor/VSEditor.cs deleted file mode 100644 index 5973145..0000000 --- a/Editor/VSEditor.cs +++ /dev/null @@ -1,335 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using Microsoft.Win32; -using UnityEditor; -using UnityEngine; -using Debug = System.Diagnostics.Debug; -using Unity.CodeEditor; -using System.Runtime.InteropServices; - - -namespace VisualStudioEditor -{ - public enum VisualStudioVersion - { - Invalid = 0, - VisualStudio2008 = 9, - VisualStudio2010 = 10, - VisualStudio2012 = 11, - VisualStudio2013 = 12, - VisualStudio2015 = 14, - VisualStudio2017 = 15, - VisualStudio2019 = 16, - } - - [InitializeOnLoad] - public class VSEditor : IExternalCodeEditor - { - static readonly string k_ExpressNotSupportedMessage = L10n.Tr( - "Unfortunately Visual Studio Express does not allow itself to be controlled by external applications. " + - "You can still use it by manually opening the Visual Studio project file, but Unity cannot automatically open files for you when you doubleclick them. " + - "\n(This does work with Visual Studio Pro)" - ); - - static VSEditor() - { - try - { - InstalledVisualStudios = Discovery.GetInstalledVisualStudios(); - } - catch (Exception ex) - { - UnityEngine.Debug.Log($@"Error detecting Visual Studio installations: {ex.Message}{Environment.NewLine}{ex.StackTrace}"); - InstalledVisualStudios = new Dictionary(); - } - var editor = new VSEditor(new Discovery(), new ProjectGeneration()); - CodeEditor.Register(editor); - var current = CodeEditor.CurrentEditorInstallation; - if (editor.TryGetInstallationForPath(current, out var installation)) - { - if (installation.Name != "MonoDevelop") - { - editor.Initialize(current); - } - return; - } - } - - const string unity_generate_all = "unity_generate_all_csproj"; - IDiscovery m_Discoverability; - IGenerator m_Generation; - CodeEditor.Installation m_Installation; - VSInitializer m_Initializer = new VSInitializer(); - - public VSEditor(IDiscovery discovery, IGenerator projectGeneration) - { - m_Discoverability = discovery; - m_Generation = projectGeneration; - } - - internal static Dictionary InstalledVisualStudios { get; private set; } - - internal static bool IsOSX => Application.platform == RuntimePlatform.OSXEditor; - internal static bool IsWindows => !IsOSX && Path.DirectorySeparatorChar == '\\' && Environment.NewLine == "\r\n"; - - public CodeEditor.Installation[] Installations => m_Discoverability.PathCallback(); - - public void CreateIfDoesntExist() - { - if (!m_Generation.HasSolutionBeenGenerated()) - { - m_Generation.Sync(); - } - } - - public bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation) - { - var lowerCasePath = editorPath.ToLower(); - if (lowerCasePath.EndsWith("vcsexpress.exe", StringComparison.OrdinalIgnoreCase)) - { - installation = new CodeEditor.Installation - { - Name = "VSExpress", - Path = editorPath - }; - m_Installation = installation; - return true; - } - - if (lowerCasePath.EndsWith("devenv.exe", StringComparison.OrdinalIgnoreCase) - || lowerCasePath.Replace(" ", "").EndsWith("visualstudio.app", StringComparison.OrdinalIgnoreCase) - || lowerCasePath.Replace(" ", "").EndsWith("visualstudio(preview).app", StringComparison.OrdinalIgnoreCase)) - { - installation = new CodeEditor.Installation - { - Name = "VisualStudio", - Path = editorPath - }; - m_Installation = installation; - return true; - } - - if (lowerCasePath.Contains("monodevelop") - || lowerCasePath.Replace(" ", "").Contains("xamarinstudio")) - { - installation = new CodeEditor.Installation - { - Name = "MonoDevelop", - Path = editorPath - }; - m_Installation = installation; - return true; - } - - installation = default; - m_Installation = installation; - return false; - } - - public void OnGUI() - { - if (m_Installation.Name.Equals("VSExpress")) - { - GUILayout.BeginHorizontal(EditorStyles.helpBox); - GUILayout.Label("", "CN EntryWarn"); - GUILayout.Label(k_ExpressNotSupportedMessage, "WordWrappedLabel"); - GUILayout.EndHorizontal(); - } - - var prevGenerate = EditorPrefs.GetBool(unity_generate_all, false); - var generateAll = EditorGUILayout.Toggle("Generate all .csproj files.", prevGenerate); - if (generateAll != prevGenerate) - { - EditorPrefs.SetBool(unity_generate_all, generateAll); - } - m_Generation.GenerateAll(generateAll); - } - - public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles, string[] importedFiles) - { - m_Generation.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles), importedFiles); - } - - public void SyncAll() - { - AssetDatabase.Refresh(); - m_Generation.Sync(); - } - - public void Initialize(string editorInstallationPath) - { - m_Initializer.Initialize(editorInstallationPath, InstalledVisualStudios); - } - - public bool OpenProject(string path, int line, int column) - { - if (m_Installation.Name == "MonoDevelop") { - return OpenAppMonoDev(path, line, column); - } - - if (IsOSX) - { - return OpenOSXApp(path, line, column); - } - - if (IsWindows) - { - return OpenWindowsApp(path, line); - } - - return false; - } - - private bool OpenWindowsApp(string path, int line) - { - var comAssetPath = AssetDatabase.FindAssets("COMIntegration a:packages").Select(AssetDatabase.GUIDToAssetPath).First(assetPath => assetPath.Contains("COMIntegration.dom")); - if (string.IsNullOrWhiteSpace(comAssetPath)) // This may be called too early where the asset database has not replicated this information yet. - { - return false; - } - UnityEditor.PackageManager.PackageInfo packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(comAssetPath); - var progpath = packageInfo.resolvedPath + comAssetPath.Substring("Packages/com.unity.ide.visualstudio".Length); - string absolutePath = ""; - if (!string.IsNullOrWhiteSpace(path)) - { - absolutePath = Path.GetFullPath(path); - } - - - var solution = GetOrGenerateSolutionFile(path); - solution = solution == "" ? "" : $"\"{solution}\""; - var process = new Process - { - StartInfo = new ProcessStartInfo - { - FileName = progpath, - Arguments = $"\"{CodeEditor.CurrentEditorInstallation}\" \"{absolutePath}\" {solution} {line}", - CreateNoWindow = true, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - } - }; - var result = process.Start(); - - while (!process.StandardOutput.EndOfStream) - { - var outputLine = process.StandardOutput.ReadLine(); - if (outputLine == "displayProgressBar") - { - EditorUtility.DisplayProgressBar("Opening Visual Studio", "Starting up Visual Studio, this might take some time.", .5f); - } - - if (outputLine == "clearprogressbar") - { - EditorUtility.ClearProgressBar(); - } - } - var errorOutput = process.StandardError.ReadToEnd(); - if (!string.IsNullOrEmpty(errorOutput)) - { - Console.WriteLine("Error: \n" + errorOutput); - } - - process.WaitForExit(); - return result; - } - - bool OpenAppMonoDev(string path, int line, int column) - { - string absolutePath = ""; - if (!string.IsNullOrWhiteSpace(path)) - { - absolutePath = Path.GetFullPath(path); - } - - var solution = GetOrGenerateSolutionFile(path); - solution = solution == "" ? "" : $"\"{solution}\""; - var pathArguments = path == "" ? "" : $"\"{path}\";{line}"; - var fileName = IsOSX ? "open" : CodeEditor.CurrentEditorInstallation; - var arguments = IsOSX - ? $"\"{CodeEditor.CurrentEditorInstallation}\" --args --nologo {solution} {pathArguments}" - : $"--nologo {solution} {pathArguments}"; - var process = new Process - { - StartInfo = new ProcessStartInfo - { - FileName = fileName, - Arguments = arguments, - CreateNoWindow = true, - UseShellExecute = true, - } - }; - - process.Start(); - - return true; - } - - [DllImport ("AppleEventIntegrationPlugin")] - static extern void OpenVisualStudio(string appPath, string solutionPath, string filePath, int line, StringBuilder sb, int sbLength); - - bool OpenOSXApp(string path, int line, int column) - { - string absolutePath = ""; - if (!string.IsNullOrWhiteSpace(path)) - { - absolutePath = Path.GetFullPath(path); - } - - string solution = GetOrGenerateSolutionFile(path); - - StringBuilder sb = new StringBuilder(4096); - - OpenVisualStudio(CodeEditor.CurrentEditorInstallation, solution, absolutePath, line, sb, sb.Capacity); - - Console.WriteLine(sb.ToString()); - - return true; - } - - private string GetOrGenerateSolutionFile(string path) - { - var solution = GetSolutionFile(path); - if (solution == "") - { - m_Generation.Sync(); - solution = GetSolutionFile(path); - } - - return solution; - } - - string GetSolutionFile(string path) - { - if (UnityEditor.Unsupported.IsDeveloperBuild()) - { - var baseFolder = GetBaseUnityDeveloperFolder(); - var lowerPath = path.ToLowerInvariant(); - var isUnitySourceCode = - lowerPath.Contains((baseFolder + "/Runtime").ToLowerInvariant()) - || lowerPath.Contains((baseFolder + "/Editor").ToLowerInvariant()); - - if (isUnitySourceCode) - { - return Path.Combine(baseFolder, "Projects/CSharp/Unity.CSharpProjects.gen.sln"); - } - } - var solutionFile = m_Generation.SolutionFile(); - if (File.Exists(solutionFile)) - { - return solutionFile; - } - return ""; - } - - static string GetBaseUnityDeveloperFolder() - { - return Directory.GetParent(EditorApplication.applicationPath).Parent.Parent.FullName; - } - } -} diff --git a/Editor/VSInitializer.cs b/Editor/VSInitializer.cs deleted file mode 100644 index 41d4809..0000000 --- a/Editor/VSInitializer.cs +++ /dev/null @@ -1,276 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text.RegularExpressions; -using Microsoft.Win32; -using UnityEngine; -using Debug = UnityEngine.Debug; - -namespace VisualStudioEditor -{ - internal class VSInitializer - { - public void Initialize(string editorPath, Dictionary installedVisualStudios) - { - switch (Application.platform) { - case RuntimePlatform.OSXEditor: - InitializeVSForMac(editorPath); - break; - case RuntimePlatform.WindowsEditor: - InitializeVisualStudio(editorPath, installedVisualStudios); - break; - } - } - - static void InitializeVSForMac(string externalEditor) - { - if (!IsVSForMac(externalEditor, out var vsfmVersion)) - return; - - var bridgeFile = GetVSForMacBridgeAssembly(externalEditor, vsfmVersion); - if (string.IsNullOrEmpty(bridgeFile) || !File.Exists(bridgeFile)) - { - Debug.Log("Unable to find Tools for Unity bridge dll for Visual Studio for Mac " + externalEditor); - return; - } - - AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(bridgeFile)); - } - - static bool IsVisualStudioForMac(string path) - { - var lowerCasePath = path.ToLower(); - var filename = Path.GetFileName(lowerCasePath).Replace(" ", ""); - return filename.StartsWith("visualstudio") && !filename.Contains("code") && filename.EndsWith(".app"); - } - - static bool IsVSForMac(string externalEditor, out Version vsfmVersion) - { - vsfmVersion = null; - - if (!IsVisualStudioForMac(externalEditor)) - return false; - - // We need to extract the version used by VS for Mac - // to lookup its addin registry - try - { - return GetVSForMacVersion(externalEditor, out vsfmVersion); - } - catch (Exception e) - { - Debug.Log("Failed to read Visual Studio for Mac information"); - Debug.LogException(e); - return false; - } - } - - static bool GetVSForMacVersion(string externalEditor, out Version vsfmVersion) - { - vsfmVersion = null; - - // Read the full VS for Mac version from the plist, it will look like this: - // - // CFBundleShortVersionString - // X.X.X.X - - var plist = Path.Combine(externalEditor, "Contents/Info.plist"); - if (!File.Exists(plist)) - return false; - - const string versionStringRegex = @"\CFBundleShortVersionString\\s+\(?\d+\.\d+\.\d+\.\d+?)\"; - - var file = File.ReadAllText(plist); - var match = Regex.Match(file, versionStringRegex); - var versionGroup = match.Groups["version"]; - if (!versionGroup.Success) - return false; - - vsfmVersion = new Version(versionGroup.Value); - return true; - } - - static void InitializeVisualStudio(string externalEditor, Dictionary installedVisualStudios) - { - if (!externalEditor.Contains("2017")) - { - return; - } - - FindVisualStudio(externalEditor, out var vsVersion, installedVisualStudios); - var bridgeFile = GetVstuBridgeAssembly(vsVersion); - if (bridgeFile == null) - { - Debug.Log("Unable to find bridge dll in registry for Microsoft Visual Studio Tools for Unity for " + externalEditor); - return; - } - if (!File.Exists(bridgeFile)) - { - Debug.Log("Unable to find bridge dll on disk for Microsoft Visual Studio Tools for Unity for " + bridgeFile); - return; - } - - AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(bridgeFile)); - } - - static string GetVstuBridgeAssembly(VisualStudioVersion version) - { - try - { - var vsVersion = string.Empty; - - switch (version) - { - // Starting with VS 15, the registry key is using the VS version - // to avoid taking a dependency on the product name - case VisualStudioVersion.VisualStudio2017: - vsVersion = "15.0"; - break; - case VisualStudioVersion.VisualStudio2019: - vsVersion = "16.0"; - break; - // VS 2015 and under are still installed in the registry - // using their project names - case VisualStudioVersion.VisualStudio2015: - vsVersion = "2015"; - break; - case VisualStudioVersion.VisualStudio2013: - vsVersion = "2013"; - break; - case VisualStudioVersion.VisualStudio2012: - vsVersion = "2012"; - break; - case VisualStudioVersion.VisualStudio2010: - vsVersion = "2010"; - break; - } - - // search first for the current user with a fallback to machine wide setting - return GetVstuBridgePathFromRegistry(vsVersion, true) - ?? GetVstuBridgePathFromRegistry(vsVersion, false); - } - catch (Exception) - { - return null; - } - } - - static string GetVstuBridgePathFromRegistry(string vsVersion, bool currentUser) - { - var registryKey = $@"{(currentUser ? "HKEY_CURRENT_USER" : "HKEY_LOCAL_MACHINE")}\Software\Microsoft\Microsoft Visual Studio {vsVersion} Tools for Unity"; - - return (string)Registry.GetValue(registryKey, "UnityExtensionPath", null); - } - - static void FindVisualStudio(string externalEditor, out VisualStudioVersion vsVersion, Dictionary installedVisualStudios) - { - if (string.IsNullOrEmpty(externalEditor)) - { - vsVersion = VisualStudioVersion.Invalid; - return; - } - - // If it's a VS found through envvars or the registry - var matches = installedVisualStudios.Where(kvp => kvp.Value.Any(v => Path.GetFullPath(v).Equals(Path.GetFullPath(externalEditor), StringComparison.OrdinalIgnoreCase))).ToArray(); - if (matches.Length > 0) - { - vsVersion = matches[0].Key; - return; - } - - // If it's a side-by-side VS selected manually - if (externalEditor.EndsWith("devenv.exe", StringComparison.OrdinalIgnoreCase)) - { - if (TryGetVisualStudioVersion(externalEditor, out vsVersion)) return; - } - - vsVersion = VisualStudioVersion.Invalid; - } - - static bool TryGetVisualStudioVersion(string externalEditor, out VisualStudioVersion vsVersion) - { - switch (ProductVersion(externalEditor).Major) - { - case 9: - vsVersion = VisualStudioVersion.VisualStudio2008; - return true; - case 10: - vsVersion = VisualStudioVersion.VisualStudio2010; - return true; - case 11: - vsVersion = VisualStudioVersion.VisualStudio2012; - return true; - case 12: - vsVersion = VisualStudioVersion.VisualStudio2013; - return true; - case 14: - vsVersion = VisualStudioVersion.VisualStudio2015; - return true; - case 15: - vsVersion = VisualStudioVersion.VisualStudio2017; - return true; - case 16: - vsVersion = VisualStudioVersion.VisualStudio2019; - return true; - } - - vsVersion = VisualStudioVersion.Invalid; - return false; - } - - static Version ProductVersion(string externalEditor) - { - try - { - return new Version(FileVersionInfo.GetVersionInfo(externalEditor).ProductVersion); - } - catch (Exception) - { - return new Version(0, 0); - } - } - - static string GetVSForMacBridgeAssembly(string externalEditor, Version vsfmVersion) - { - // Check first if we're overriden - // Useful when developing UnityVS for Mac - var bridge = Environment.GetEnvironmentVariable("VSTUM_BRIDGE"); - if (!string.IsNullOrEmpty(bridge) && File.Exists(bridge)) - return bridge; - - // Look for installed addin - const string addinBridge = "Editor/SyntaxTree.VisualStudio.Unity.Bridge.dll"; - const string addinName = "MonoDevelop.Unity"; - - // Check if we're installed in the user addins repository - // ~/Library/Application Support/VisualStudio/X.0/LocalInstall/Addins - var localAddins = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.Personal), - "Library/Application Support/VisualStudio/" + vsfmVersion.Major + ".0" + "/LocalInstall/Addins"); - - // In the user addins repository, the addins are suffixed by their versions, like `MonoDevelop.Unity.1.0` - // When installing another local user addin, MD will remove files inside the folder - // So we browse all VSTUM addins, and return the one with a bridge, which is the one MD will load - if (Directory.Exists(localAddins)) - { - foreach (var folder in Directory.GetDirectories(localAddins, addinName + "*", SearchOption.TopDirectoryOnly)) - { - bridge = Path.Combine(folder, addinBridge); - if (File.Exists(bridge)) - return bridge; - } - } - - // Check in Visual Studio.app/ - // In that case the name of the addin is used - bridge = Path.Combine(externalEditor, "Contents/Resources/lib/monodevelop/AddIns/" + addinName + "/" + addinBridge); - if (File.Exists(bridge)) - return bridge; - - return null; - } - } -} diff --git a/Editor/VSWhere.meta b/Editor/VSWhere.meta index 522b5a1..681e580 100644 --- a/Editor/VSWhere.meta +++ b/Editor/VSWhere.meta @@ -1,8 +1,8 @@ -fileFormatVersion: 2 -guid: 5b17896803f77494da73d73448fb6cb4 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 5b17896803f77494da73d73448fb6cb4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/VSWhere/vswhere.exe.meta b/Editor/VSWhere/vswhere.exe.meta index 98d3694..3e707c0 100644 --- a/Editor/VSWhere/vswhere.exe.meta +++ b/Editor/VSWhere/vswhere.exe.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: 585c3fb85b32bd64e8814074e754163e -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 585c3fb85b32bd64e8814074e754163e +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/VisualStudioEditor.cs b/Editor/VisualStudioEditor.cs new file mode 100644 index 0000000..44506c4 --- /dev/null +++ b/Editor/VisualStudioEditor.cs @@ -0,0 +1,258 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Unity Technologies. + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using UnityEditor; +using UnityEngine; +using Unity.CodeEditor; +using System.Runtime.InteropServices; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + [InitializeOnLoad] + public class VisualStudioEditor : IExternalCodeEditor + { + private static readonly VisualStudioInstallation[] _installations; + + internal static bool IsOSX => Application.platform == RuntimePlatform.OSXEditor; + internal static bool IsWindows => !IsOSX && Path.DirectorySeparatorChar == '\\' && Environment.NewLine == "\r\n"; + + CodeEditor.Installation[] IExternalCodeEditor.Installations => _installations + .Select(i => i.ToCodeEditorInstallation()) + .ToArray(); + + private readonly IGenerator _generator = new ProjectGeneration(); + + static VisualStudioEditor() + { + try + { + _installations = Discovery + .GetVisualStudioInstallations() + .ToArray(); + } + catch (Exception ex) + { + UnityEngine.Debug.Log($"Error detecting Visual Studio installations: {ex}"); + _installations = Array.Empty(); + } + + CodeEditor.Register(new VisualStudioEditor()); + } + + public void CreateIfDoesntExist() + { + if (!_generator.HasSolutionBeenGenerated()) + _generator.Sync(); + } + + public void Initialize(string editorInstallationPath) + { + } + + internal bool TryGetVisualStudioInstallationForPath(string editorPath, out VisualStudioInstallation installation) + { + // lookup for well known installations + foreach (var candidate in _installations) + { + if (!string.Equals(Path.GetFullPath(editorPath), Path.GetFullPath(candidate.Path), StringComparison.OrdinalIgnoreCase)) + continue; + + installation = candidate; + return true; + } + + return Discovery.TryDiscoverInstallation(editorPath, out installation); + } + + public bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation) + { + var result = TryGetVisualStudioInstallationForPath(editorPath, out var vsi); + installation = vsi == null ? default : vsi.ToCodeEditorInstallation(); + return result; + } + + public void OnGUI() + { + const string unity_generate_all = "unity_generate_all_csproj"; + + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + + var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(GetType().Assembly); + + var style = new GUIStyle + { + richText = true, + margin = new RectOffset(0, 4, 0, 0) + }; + + GUILayout.Label($"{package.displayName} v{package.version} enabled", style); + GUILayout.EndHorizontal(); + + var prevGenerate = EditorPrefs.GetBool(unity_generate_all, false); + var generateAll = EditorGUILayout.Toggle("Generate all .csproj files.", prevGenerate); + if (generateAll != prevGenerate) + { + EditorPrefs.SetBool(unity_generate_all, generateAll); + } + + _generator.GenerateAll(generateAll); + } + + public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles, string[] importedFiles) + { + _generator.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles), importedFiles); + + foreach (var file in importedFiles.Where(a => Path.GetExtension(a) == ".pdb")) + { + var pdbFile = FileUtility.GetAssetFullPath(file); + if (Symbols.IsPortableSymbolFile(pdbFile)) + continue; + + UnityEngine.Debug.LogWarning($"Unity is only able to load mdb or portable-pdb symbols. {file} is using a legacy pdb format."); + } + } + + public void SyncAll() + { + AssetDatabase.Refresh(); + _generator.Sync(); + } + + bool IsSupportedPath(string path) + { + // Path is empty with "Open C# Project", as we only want to open the solution without specific files + if (string.IsNullOrEmpty(path)) + return true; + + // cs, uxml, uss, shader, compute, cginc, hlsl, glslinc, template are part of Unity builtin extensions + // txt, xml, fnt, cd are -often- par of Unity user extensions + // asdmdef is mandatory included + if (_generator.IsSupportedFile(path)) + return true; + + return false; + } + + public bool OpenProject(string path, int line, int column) + { + if (!IsSupportedPath(path)) + return false; + + if (IsOSX) + return OpenOSXApp(path, line, column); + + if (IsWindows) + return OpenWindowsApp(path, line); + + return false; + } + + private bool OpenWindowsApp(string path, int line) + { + var progpath = FileUtility + .FindPackageAssetFullPath("COMIntegration a:packages", "COMIntegration.exe") + .FirstOrDefault(); + + if (string.IsNullOrWhiteSpace(progpath)) + return false; + + string absolutePath = ""; + if (!string.IsNullOrWhiteSpace(path)) + { + absolutePath = Path.GetFullPath(path); + } + + // We remove all invalid chars from the solution filename, but we cannot prevent the user from using a specific path for the Unity project + // So process the fullpath to make it compatible with VS + var solution = GetOrGenerateSolutionFile(path); + if (!string.IsNullOrWhiteSpace(solution)) + { + solution = $"\"{solution}\""; + solution = solution.Replace("^", "^^"); + } + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = progpath, + Arguments = $"\"{CodeEditor.CurrentEditorInstallation}\" \"{absolutePath}\" {solution} {line}", + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + } + }; + var result = process.Start(); + + while (!process.StandardOutput.EndOfStream) + { + var outputLine = process.StandardOutput.ReadLine(); + if (outputLine == "displayProgressBar") + { + EditorUtility.DisplayProgressBar("Opening Visual Studio", "Starting up Visual Studio, this might take some time.", .5f); + } + + if (outputLine == "clearprogressbar") + { + EditorUtility.ClearProgressBar(); + } + } + + var errorOutput = process.StandardError.ReadToEnd(); + if (!string.IsNullOrEmpty(errorOutput)) + { + Console.WriteLine("Error: \n" + errorOutput); + } + + process.WaitForExit(); + return result; + } + + [DllImport("AppleEventIntegration")] + static extern bool OpenVisualStudio(string appPath, string solutionPath, string filePath, int line); + + bool OpenOSXApp(string path, int line, int column) + { + string absolutePath = ""; + if (!string.IsNullOrWhiteSpace(path)) + { + absolutePath = Path.GetFullPath(path); + } + + string solution = GetOrGenerateSolutionFile(path); + return OpenVisualStudio(CodeEditor.CurrentEditorInstallation, solution, absolutePath, line); + } + + private string GetOrGenerateSolutionFile(string path) + { + var solution = GetSolutionFile(path); + if (solution == "") + { + _generator.Sync(); + solution = GetSolutionFile(path); + } + + return solution; + } + + string GetSolutionFile(string path) + { + var solutionFile = _generator.SolutionFile(); + if (File.Exists(solutionFile)) + { + return solutionFile; + } + + return ""; + } + } +} diff --git a/Editor/VSEditor.cs.meta b/Editor/VisualStudioEditor.cs.meta similarity index 95% rename from Editor/VSEditor.cs.meta rename to Editor/VisualStudioEditor.cs.meta index 9d8987f..bdf0360 100644 --- a/Editor/VSEditor.cs.meta +++ b/Editor/VisualStudioEditor.cs.meta @@ -1,11 +1,11 @@ -fileFormatVersion: 2 -guid: 0173aff8c07e06b42af07ebdd7f08032 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 0173aff8c07e06b42af07ebdd7f08032 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/VisualStudioInstallation.cs b/Editor/VisualStudioInstallation.cs new file mode 100644 index 0000000..45f900e --- /dev/null +++ b/Editor/VisualStudioInstallation.cs @@ -0,0 +1,126 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using Microsoft.Win32; +using Unity.CodeEditor; +using IOPath = System.IO.Path; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + internal class VisualStudioInstallation + { + public string Name { get; set; } + public string Path { get; set; } + public Version Version { get; set; } + public bool IsPrerelease { get; set; } + + public bool SupportsAnalyzers + { + get + { + if (VisualStudioEditor.IsWindows) + return Version >= new Version(16, 3); + + if (VisualStudioEditor.IsOSX) + return Version >= new Version(8, 3); + + return false; + } + } + + private static string ReadRegistry(RegistryKey hive, string keyName, string valueName) + { + try + { + var unitykey = hive.OpenSubKey(keyName); + + var result = (string)unitykey?.GetValue(valueName); + return result; + } + catch (Exception) + { + return null; + } + } + + // We only use this to find analyzers, we do not need to load this assembly anymore + private string GetBridgeLocation() + { + if (VisualStudioEditor.IsWindows) + { + // Registry, using legacy bridge location + var keyName = $"Software\\Microsoft\\Microsoft Visual Studio {Version.Major}.0 Tools for Unity"; + const string valueName = "UnityExtensionPath"; + + var bridge = ReadRegistry(Registry.CurrentUser, keyName, valueName); + if (string.IsNullOrEmpty(bridge)) + bridge = ReadRegistry(Registry.LocalMachine, keyName, valueName); + + return bridge; + } + + if (VisualStudioEditor.IsOSX) + { + // Environment, useful when developing UnityVS for Mac + var bridge = Environment.GetEnvironmentVariable("VSTUM_BRIDGE"); + if (!string.IsNullOrEmpty(bridge) && File.Exists(bridge)) + return bridge; + + const string addinBridge = "Editor/SyntaxTree.VisualStudio.Unity.Bridge.dll"; + const string addinName = "MonoDevelop.Unity"; + + // user addins repository + var localAddins = IOPath.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.Personal), + $"Library/Application Support/VisualStudio/${Version.Major}.0" + "/LocalInstall/Addins"); + + // In the user addins repository, the addins are suffixed by their versions, like `MonoDevelop.Unity.1.0` + // When installing another local user addin, MD will remove files inside the folder + // So we browse all VSTUM addins, and return the one with a bridge, which is the one MD will load + if (Directory.Exists(localAddins)) + { + foreach (var folder in Directory.GetDirectories(localAddins, addinName + "*", SearchOption.TopDirectoryOnly)) + { + bridge = IOPath.Combine(folder, addinBridge); + if (File.Exists(bridge)) + return bridge; + } + } + + // Check in Visual Studio.app/ + // In that case the name of the addin is used + bridge = IOPath.Combine(Path, $"Contents/Resources/lib/monodevelop/AddIns/{addinName}/{addinBridge}"); + if (File.Exists(bridge)) + return bridge; + } + + return null; + } + + public string[] GetAnalyzers() + { + var bridge = GetBridgeLocation(); + + if (!string.IsNullOrEmpty(bridge)) + { + var baseLocation = IOPath.Combine(IOPath.GetDirectoryName(bridge), ".."); + var analyzerLocation = IOPath.GetFullPath(IOPath.Combine(baseLocation, "Analyzers")); + + if (Directory.Exists(analyzerLocation)) + return Directory.GetFiles(analyzerLocation, "*Analyzers.dll", SearchOption.AllDirectories); + } + + // Local assets + // return FileUtility.FindPackageAssetFullPath("Analyzers a:packages", ".Analyzers.dll"); + return Array.Empty(); + } + + public CodeEditor.Installation ToCodeEditorInstallation() + { + return new CodeEditor.Installation() { Name = Name, Path = Path }; + } + } +} diff --git a/Editor/VisualStudioInstallation.cs.meta b/Editor/VisualStudioInstallation.cs.meta new file mode 100644 index 0000000..b3aa988 --- /dev/null +++ b/Editor/VisualStudioInstallation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bb86eea06f54fb24caa7046a8a764945 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/VisualStudioIntegration.cs b/Editor/VisualStudioIntegration.cs new file mode 100644 index 0000000..e1c8873 --- /dev/null +++ b/Editor/VisualStudioIntegration.cs @@ -0,0 +1,174 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using Microsoft.Unity.VisualStudio.Editor.Messaging; +using UnityEditor; +using UnityEngine; +using MessageType = Microsoft.Unity.VisualStudio.Editor.Messaging.MessageType; + +namespace Microsoft.Unity.VisualStudio.Editor +{ + [InitializeOnLoad] + internal class VisualStudioIntegration + { + private static Messager _messager; + + private static readonly Queue Incoming = new Queue(); + private static readonly object IncomingLock = new object(); + + public static Application.LogCallback LogCallback = delegate { }; + + static VisualStudioIntegration() + { + RunOnceOnUpdate(() => + { + _messager = Messager.BindTo(MessagingPort()); + _messager.ReceiveMessage += ReceiveMessage; + + RunOnShutdown(Shutdown); + }); + + EditorApplication.update += OnUpdate; + } + + private static void RunOnceOnUpdate(Action action) + { + var callback = null as EditorApplication.CallbackFunction; + + callback = () => + { + EditorApplication.update -= callback; + action(); + }; + + EditorApplication.update += callback; + } + + private static void RunOnShutdown(Action action) + { + // Mono on OSX has all kinds of quirks on AppDomain shutdown + if (!VisualStudioEditor.IsWindows) + return; + + AppDomain.CurrentDomain.DomainUnload += (_, __) => action(); + } + + private static int DebuggingPort() + { + return 56000 + (System.Diagnostics.Process.GetCurrentProcess().Id % 1000); + } + + private static int MessagingPort() + { + return DebuggingPort() + 2; + } + + private static void ReceiveMessage(object sender, MessageEventArgs args) + { + OnMessage(args.Message); + } + + private static void OnUpdate() + { + lock (IncomingLock) + { + while (Incoming.Count > 0) + { + ProcessIncoming(Incoming.Dequeue()); + } + } + } + + private static void AddMessage(Message message) + { + lock (IncomingLock) + { + Incoming.Enqueue(message); + } + } + + private static void ProcessIncoming(Message message) + { + switch (message.Type) + { + case MessageType.Ping: + Answer(message, MessageType.Pong); + break; + case MessageType.Play: + Shutdown(); + EditorApplication.isPlaying = true; + break; + case MessageType.Stop: + EditorApplication.isPlaying = false; + break; + case MessageType.Pause: + EditorApplication.isPaused = true; + break; + case MessageType.Unpause: + EditorApplication.isPaused = false; + break; + case MessageType.Build: + // Not used anymore + break; + case MessageType.Refresh: + Refresh(); + break; + case MessageType.Version: + Answer(message, MessageType.Version, PackageVersion()); + break; + case MessageType.UpdatePackage: + // Not used anymore + break; + case MessageType.ProjectPath: + Answer(message, MessageType.ProjectPath, Path.GetFullPath(Path.Combine(Application.dataPath, ".."))); + break; + } + } + + private static string PackageVersion() + { + var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(VisualStudioIntegration).Assembly); + return package.version; + } + + private static void Refresh() + { + RunOnceOnUpdate(AssetDatabase.Refresh); + } + + private static void OnMessage(Message message) + { + AddMessage(message); + } + + private static void Answer(Message message, MessageType answerType, string answerValue = "") + { + var targetEndPoint = message.Origin; + + Answer( + targetEndPoint, + answerType, + answerValue); + } + + private static void Answer(IPEndPoint targetEndPoint, MessageType answerType, string answerValue) + { + _messager?.SendMessage(targetEndPoint, answerType, answerValue); + } + + private static void Shutdown() + { + if (_messager == null) + return; + + _messager.ReceiveMessage -= ReceiveMessage; + _messager.Dispose(); + _messager = null; + } + } +} diff --git a/Editor/VisualStudioIntegration.cs.meta b/Editor/VisualStudioIntegration.cs.meta new file mode 100644 index 0000000..30baf7c --- /dev/null +++ b/Editor/VisualStudioIntegration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 48fcd6ebd5ce8fd4cbe931895233677d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/com.unity.ide.visualstudio.asmdef b/Editor/com.unity.ide.visualstudio.asmdef index 5ad8d8e..6f75d98 100644 --- a/Editor/com.unity.ide.visualstudio.asmdef +++ b/Editor/com.unity.ide.visualstudio.asmdef @@ -1,9 +1,9 @@ -{ - "name": "Unity.VisualStudio.Editor", - "references": [], - "optionalUnityReferences": [], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [] -} +{ + "name": "Unity.VisualStudio.Editor", + "references": [], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [] +} diff --git a/Editor/com.unity.ide.visualstudio.asmdef.meta b/Editor/com.unity.ide.visualstudio.asmdef.meta index 899f13c..0b1887f 100644 --- a/Editor/com.unity.ide.visualstudio.asmdef.meta +++ b/Editor/com.unity.ide.visualstudio.asmdef.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: b93f844d45cfcc44fa2b0eed5c9ec6bb -AssemblyDefinitionImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: b93f844d45cfcc44fa2b0eed5c9ec6bb +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LICENSE.md b/LICENSE.md index 8098f2d..c4c4725 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,21 +1,22 @@ -MIT License - -Copyright (c) 2019 Unity Technologies - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +MIT License + +Copyright (c) 2019 Unity Technologies +Copyright (c) 2019 Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/LICENSE.md.meta b/LICENSE.md.meta index df06dd0..eb7cb2a 100644 --- a/LICENSE.md.meta +++ b/LICENSE.md.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: 1fe9e6e1ae93cf64bbdfbd29300752e1 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 1fe9e6e1ae93cf64bbdfbd29300752e1 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/ThirdPartyNotices.md b/ThirdPartyNotices.md index e03e636..fa8f45d 100644 --- a/ThirdPartyNotices.md +++ b/ThirdPartyNotices.md @@ -1,31 +1,31 @@ -This package contains third-party software components governed by the license(s) indicated below: ---------- - -Component Name: VSWhere - -License Type: "MIT" - -The MIT License (MIT) -Copyright (C) Microsoft Corporation. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---------- -Component Name: benbuck/EnvDTE - -License Type: Zero-Clause BSD - -Permission to use, copy, modify, and/or distribute this software for any purpose -with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +This package contains third-party software components governed by the license(s) indicated below: +--------- + +Component Name: VSWhere + +License Type: "MIT" + +The MIT License (MIT) +Copyright (C) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--------- +Component Name: benbuck/EnvDTE + +License Type: Zero-Clause BSD + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/ThirdPartyNotices.md.meta b/ThirdPartyNotices.md.meta index e7f61ce..c61f73b 100644 --- a/ThirdPartyNotices.md.meta +++ b/ThirdPartyNotices.md.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: 7809f42f64c877f4b90ac233e5ec2372 -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 7809f42f64c877f4b90ac233e5ec2372 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/package.json b/package.json index 22fcd54..a22ff54 100644 --- a/package.json +++ b/package.json @@ -2,16 +2,16 @@ "name": "com.unity.ide.visualstudio", "displayName": "Visual Studio Editor", "description": "Code editor integration for supporting Visual Studio as code editor for unity. Adds support for generating csproj files for intellisense purposes, auto discovery of installations, etc.", - "version": "1.0.11", - "unity": "2019.2", + "version": "2.0.0", + "unity": "2020.1", "unityRelease": "0a12", "dependencies": {}, "relatedPackages": { - "com.unity.ide.visualstudio.tests": "1.0.5" + "com.unity.ide.visualstudio.tests": "2.0.0" }, "repository": { "type": "git", "url": "git@github.cds.internal.unity3d.com:unity/com.unity.ide.visualstudio.git", - "revision": "7378597cbd075d617aade65f1aa9c13a22c00d1c" + "revision": "a3fbcc6d9504b41b441ecf6caeb3bbc753d6d010" } } diff --git a/package.json.meta b/package.json.meta index ed41749..d0c5459 100644 --- a/package.json.meta +++ b/package.json.meta @@ -1,7 +1,7 @@ -fileFormatVersion: 2 -guid: 656f74f6edaa396458412b9e3903d8cd -PackageManifestImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: +fileFormatVersion: 2 +guid: 656f74f6edaa396458412b9e3903d8cd +PackageManifestImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: