diff --git a/Roslyn.sln b/Roslyn.sln index 79850854925e1..412e1d9c03896 100644 --- a/Roslyn.sln +++ b/Roslyn.sln @@ -117,8 +117,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpScriptingTest", "src\ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveFeatures", "src\Interactive\Features\InteractiveFeatures.csproj", "{8E2A252E-A140-45A6-A81A-2652996EA589}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveWindow", "src\InteractiveWindow\Editor\InteractiveWindow.csproj", "{01E9BD68-0339-4A13-B42F-A3CA84D164F3}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpEditorServicesTest", "src\EditorFeatures\CSharpTest\CSharpEditorServicesTest.csproj", "{AC2BCEFB-9298-4621-AC48-1FF5E639E48D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpEditorServicesTest2", "src\EditorFeatures\CSharpTest2\CSharpEditorServicesTest2.csproj", "{16E93074-4252-466C-89A3-3B905ABAF779}" @@ -143,10 +141,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "csi", "src\Interactive\csi\ EndProject Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "vbi", "src\Interactive\vbi\vbi.vbproj", "{6E62A0FF-D0DC-4109-9131-AB8E60CDFF7B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveWindowTest", "src\InteractiveWindow\EditorTest\InteractiveWindowTest.csproj", "{7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VisualStudioInteractiveWindow", "src\InteractiveWindow\VisualStudio\VisualStudioInteractiveWindow.csproj", "{20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServicesVisualStudio", "src\VisualStudio\Core\Def\ServicesVisualStudio.csproj", "{86FD5B9A-4FA0-4B10-B59F-CFAF077A859C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServicesVisualStudioImpl", "src\VisualStudio\Core\Impl\ServicesVisualStudioImpl.csproj", "{C0E80510-4FBE-4B0C-AF2C-4F473787722C}" @@ -1420,26 +1414,6 @@ Global {8E2A252E-A140-45A6-A81A-2652996EA589}.Release|x64.Build.0 = Release|Any CPU {8E2A252E-A140-45A6-A81A-2652996EA589}.Release|x86.ActiveCfg = Release|Any CPU {8E2A252E-A140-45A6-A81A-2652996EA589}.Release|x86.Build.0 = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|ARM.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|ARM.Build.0 = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|x64.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|x64.Build.0 = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|x86.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|x86.Build.0 = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Any CPU.Build.0 = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|ARM.ActiveCfg = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|ARM.Build.0 = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|x64.ActiveCfg = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|x64.Build.0 = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|x86.ActiveCfg = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|x86.Build.0 = Release|Any CPU {AC2BCEFB-9298-4621-AC48-1FF5E639E48D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {AC2BCEFB-9298-4621-AC48-1FF5E639E48D}.Debug|Any CPU.Build.0 = Debug|Any CPU {AC2BCEFB-9298-4621-AC48-1FF5E639E48D}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -1674,46 +1648,6 @@ Global {6E62A0FF-D0DC-4109-9131-AB8E60CDFF7B}.Release|x64.Build.0 = Release|Any CPU {6E62A0FF-D0DC-4109-9131-AB8E60CDFF7B}.Release|x86.ActiveCfg = Release|Any CPU {6E62A0FF-D0DC-4109-9131-AB8E60CDFF7B}.Release|x86.Build.0 = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|ARM.ActiveCfg = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|ARM.Build.0 = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|x64.ActiveCfg = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|x64.Build.0 = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|x86.ActiveCfg = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|x86.Build.0 = Debug|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|Any CPU.Build.0 = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|ARM.ActiveCfg = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|ARM.Build.0 = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|x64.ActiveCfg = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|x64.Build.0 = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|x86.ActiveCfg = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|x86.Build.0 = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|ARM.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|ARM.Build.0 = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|x64.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|x64.Build.0 = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|x86.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|x86.Build.0 = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Any CPU.Build.0 = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|ARM.ActiveCfg = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|ARM.Build.0 = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|x64.ActiveCfg = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|x64.Build.0 = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|x86.ActiveCfg = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|x86.Build.0 = Release|Any CPU {86FD5B9A-4FA0-4B10-B59F-CFAF077A859C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {86FD5B9A-4FA0-4B10-B59F-CFAF077A859C}.Debug|Any CPU.Build.0 = Debug|Any CPU {86FD5B9A-4FA0-4B10-B59F-CFAF077A859C}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -3233,7 +3167,6 @@ Global {066F0DBD-C46C-4C20-AFEC-99829A172625} = {38940C5F-97FD-4B2A-B2CD-C4E4EF601B05} {2DAE4406-7A89-4B5F-95C3-BC5422CE47CE} = {38940C5F-97FD-4B2A-B2CD-C4E4EF601B05} {8E2A252E-A140-45A6-A81A-2652996EA589} = {2491A9B9-C0A8-49EE-9077-A32DE76E1E94} - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} = {999FBDA2-33DA-4F74-B957-03AC72CCE5EC} {AC2BCEFB-9298-4621-AC48-1FF5E639E48D} = {EE97CB90-33BB-4F3A-9B3D-69375DEC6AC6} {16E93074-4252-466C-89A3-3B905ABAF779} = {EE97CB90-33BB-4F3A-9B3D-69375DEC6AC6} {8CEE3609-A5A9-4A9B-86D7-33118F5D6B33} = {EE97CB90-33BB-4F3A-9B3D-69375DEC6AC6} @@ -3246,8 +3179,6 @@ Global {8CEE3609-A5A9-4A9B-86D7-33118F5D6B34} = {5CA5F70E-0FDB-467B-B22C-3CD5994F0087} {14118347-ED06-4608-9C45-18228273C712} = {5CA5F70E-0FDB-467B-B22C-3CD5994F0087} {6E62A0FF-D0DC-4109-9131-AB8E60CDFF7B} = {5CA5F70E-0FDB-467B-B22C-3CD5994F0087} - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3} = {999FBDA2-33DA-4F74-B957-03AC72CCE5EC} - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} = {999FBDA2-33DA-4F74-B957-03AC72CCE5EC} {86FD5B9A-4FA0-4B10-B59F-CFAF077A859C} = {8DBA5174-B0AA-4561-82B1-A46607697753} {C0E80510-4FBE-4B0C-AF2C-4F473787722C} = {8DBA5174-B0AA-4561-82B1-A46607697753} {7BE3DEEB-87F8-4E15-9C21-4F94B0B1C2D6} = {8DBA5174-B0AA-4561-82B1-A46607697753} diff --git a/build/config/SignToolData.json b/build/config/SignToolData.json index d837a6b2d20ae..6d0b33030708a 100644 --- a/build/config/SignToolData.json +++ b/build/config/SignToolData.json @@ -37,7 +37,6 @@ "Microsoft.DiaSymReader.PortablePdb.dll", "Microsoft.VisualStudio.CSharp.Repl.dll", "Microsoft.VisualStudio.InteractiveServices.dll", - "Microsoft.VisualStudio.InteractiveWindow.dll", "Microsoft.VisualStudio.LanguageServices.CSharp.dll", "Microsoft.VisualStudio.LanguageServices.dll", "Microsoft.VisualStudio.LanguageServices.Implementation.dll", @@ -46,7 +45,6 @@ "Microsoft.VisualStudio.LanguageServices.VisualBasic.dll", "Microsoft.VisualStudio.LanguageServices.Xaml.dll", "Microsoft.VisualStudio.VisualBasic.Repl.dll", - "Microsoft.VisualStudio.VsInteractiveWindow.dll", "Pdb2Xml.exe", "Roslyn.Compilers.Extension.dll", "Roslyn.Hosting.Diagnostics.dll", @@ -90,7 +88,6 @@ "strongName": null, "values": [ "ExpressionEvaluatorPackage.vsix", - "Microsoft.VisualStudio.VsInteractiveWindow.vsix", "Roslyn.Compilers.Extension.vsix", "Roslyn.Deployment.Full.vsix", "Roslyn.Deployment.Full.Next.vsix", diff --git a/src/Deployment/Roslyn.csproj b/src/Deployment/Roslyn.csproj index 4464174ab6efc..b3441fc607eee 100644 --- a/src/Deployment/Roslyn.csproj +++ b/src/Deployment/Roslyn.csproj @@ -44,13 +44,6 @@ false VSIXContainerProjectOutputGroup%3b - - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} - VisualStudioInteractiveWindow - Vsixes - false - VSIXContainerProjectOutputGroup%3b - {C467FEFA-337D-4705-BB5A-BDF41A555FDC} VisualStudioSetupInteractive @@ -74,4 +67,4 @@ - + \ No newline at end of file diff --git a/src/Deployment/source.extension.vsixmanifest b/src/Deployment/source.extension.vsixmanifest index a9d58d518fac7..919d735694f1e 100644 --- a/src/Deployment/source.extension.vsixmanifest +++ b/src/Deployment/source.extension.vsixmanifest @@ -29,15 +29,6 @@ Location="|VisualStudioSetup;VSIXContainerProjectOutputGroup|" Id="|VisualStudioSetup;VSIXIdentifierProjectOutputGroup|" /> - - {8E2A252E-A140-45A6-A81A-2652996EA589} InteractiveFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures diff --git a/src/EditorFeatures/CSharpTest/project.json b/src/EditorFeatures/CSharpTest/project.json index 722161ece64e1..5d2b101df3582 100644 --- a/src/EditorFeatures/CSharpTest/project.json +++ b/src/EditorFeatures/CSharpTest/project.json @@ -4,6 +4,10 @@ "version": "14.3.25407", "suppressParent": "all" }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal": { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.VisualStudio.Language.CallHierarchy": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj b/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj index a8ed0f856fc82..da9ef996c56b4 100644 --- a/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj +++ b/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj @@ -51,10 +51,6 @@ {8E2A252E-A140-45A6-A81A-2652996EA589} InteractiveFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures diff --git a/src/EditorFeatures/Core/EditorFeatures.csproj b/src/EditorFeatures/Core/EditorFeatures.csproj index 2a4f0143bd390..0e934b5966d19 100644 --- a/src/EditorFeatures/Core/EditorFeatures.csproj +++ b/src/EditorFeatures/Core/EditorFeatures.csproj @@ -40,10 +40,6 @@ {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - true diff --git a/src/EditorFeatures/Core/project.json b/src/EditorFeatures/Core/project.json index 79161ac3e8b82..77cfff01e1bb4 100644 --- a/src/EditorFeatures/Core/project.json +++ b/src/EditorFeatures/Core/project.json @@ -1,6 +1,14 @@ { "dependencies": { "System.Collections.Immutable": "1.2.0", + "Microsoft.VisualStudio.InteractiveWindow": { + "version": "2.0.0-beta5-60820-04", + "suppressParent": "all" + }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal": { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.VisualStudio.Language.CallHierarchy": { "version": "14.3.25407", "suppressParent": "all" @@ -9,6 +17,10 @@ "version": "14.3.25407", "suppressParent": "all" }, + "Microsoft.VisualStudio.Language.StandardClassification": { + "version": "14.3.25407", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Language.Intellisense": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/EditorFeatures/Next/EditorFeatures.Next.csproj b/src/EditorFeatures/Next/EditorFeatures.Next.csproj index cceaf345eb59a..23d519d6fded0 100644 --- a/src/EditorFeatures/Next/EditorFeatures.Next.csproj +++ b/src/EditorFeatures/Next/EditorFeatures.Next.csproj @@ -43,11 +43,6 @@ {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - InteractiveWindow - true diff --git a/src/EditorFeatures/Test/EditorServicesTest.csproj b/src/EditorFeatures/Test/EditorServicesTest.csproj index d83c87e120528..d8020f03d0d7b 100644 --- a/src/EditorFeatures/Test/EditorServicesTest.csproj +++ b/src/EditorFeatures/Test/EditorServicesTest.csproj @@ -87,10 +87,6 @@ {8E2A252E-A140-45A6-A81A-2652996EA589} InteractiveFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures diff --git a/src/EditorFeatures/Test/project.json b/src/EditorFeatures/Test/project.json index 45626f1b2a425..03e484e86f561 100644 --- a/src/EditorFeatures/Test/project.json +++ b/src/EditorFeatures/Test/project.json @@ -7,6 +7,10 @@ "version": "14.3.25407", "suppressParent": "all" }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal" : { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.VisualStudio.Language.CallHierarchy": { "version": "14.3.25407", "suppressParent": "all" @@ -15,6 +19,10 @@ "version": "14.3.25407", "suppressParent": "all" }, + "Microsoft.VisualStudio.Language.StandardClassification": { + "version": "14.3.25407", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Text.UI": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/EditorFeatures/Test2/EditorServicesTest2.vbproj b/src/EditorFeatures/Test2/EditorServicesTest2.vbproj index bee08878508fb..2b1ce8faf6918 100644 --- a/src/EditorFeatures/Test2/EditorServicesTest2.vbproj +++ b/src/EditorFeatures/Test2/EditorServicesTest2.vbproj @@ -25,10 +25,6 @@ {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6} BasicCodeAnalysis - - {01e9bd68-0339-4a13-b42f-a3ca84d164f3} - InteractiveWindow - {92412d1a-0f23-45b5-b196-58839c524917} InteractiveEditorFeatures diff --git a/src/EditorFeatures/Test2/project.json b/src/EditorFeatures/Test2/project.json index 4e21b993d96d7..808643fa1b265 100644 --- a/src/EditorFeatures/Test2/project.json +++ b/src/EditorFeatures/Test2/project.json @@ -1,9 +1,17 @@ { "dependencies": { + "Microsoft.VisualStudio.InteractiveWindow": { + "version": "2.0.0-beta5-60820-04", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Language.Intellisense": { "version": "14.3.25407", "suppressParent": "all" }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal": { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.VisualStudio.Language.CallHierarchy": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/EditorFeatures/TestUtilities/project.json b/src/EditorFeatures/TestUtilities/project.json index 18965b3c8699e..761bb8af4b7c5 100644 --- a/src/EditorFeatures/TestUtilities/project.json +++ b/src/EditorFeatures/TestUtilities/project.json @@ -12,10 +12,18 @@ "version": "14.2.19-pre", "suppressParent": "all" }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal": { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.VisualStudio.Platform.VSEditor": { "version": "14.3.25407", "suppressParent": "all" }, + "Microsoft.VisualStudio.Language.StandardClassification" : { + "version": "14.3.25407", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Language.Intellisense": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/EditorFeatures/VisualBasicTest/project.json b/src/EditorFeatures/VisualBasicTest/project.json index 470c679f3a07f..a1dbadbc1bb70 100644 --- a/src/EditorFeatures/VisualBasicTest/project.json +++ b/src/EditorFeatures/VisualBasicTest/project.json @@ -4,6 +4,10 @@ "version": "14.3.25407", "suppressParent": "all" }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal": { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.VisualStudio.Language.NavigateTo.Interfaces": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/Interactive/EditorFeatures/CSharp/CSharpInteractiveEditorFeatures.csproj b/src/Interactive/EditorFeatures/CSharp/CSharpInteractiveEditorFeatures.csproj index 39407c19fbc97..05f924469944a 100644 --- a/src/Interactive/EditorFeatures/CSharp/CSharpInteractiveEditorFeatures.csproj +++ b/src/Interactive/EditorFeatures/CSharp/CSharpInteractiveEditorFeatures.csproj @@ -52,10 +52,6 @@ {8E2A252E-A140-45A6-A81A-2652996EA589} InteractiveFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures diff --git a/src/Interactive/EditorFeatures/CSharp/project.json b/src/Interactive/EditorFeatures/CSharp/project.json index 0ef014f0ada83..2017e667f28da 100644 --- a/src/Interactive/EditorFeatures/CSharp/project.json +++ b/src/Interactive/EditorFeatures/CSharp/project.json @@ -1,5 +1,9 @@ { "dependencies": { + "Microsoft.VisualStudio.InteractiveWindow": { + "version": "2.0.0-beta5-60820-04", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Text.UI.Wpf": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/Interactive/EditorFeatures/Core/InteractiveEditorFeatures.csproj b/src/Interactive/EditorFeatures/Core/InteractiveEditorFeatures.csproj index 2d775e0bee35a..f1b893a1686c0 100644 --- a/src/Interactive/EditorFeatures/Core/InteractiveEditorFeatures.csproj +++ b/src/Interactive/EditorFeatures/Core/InteractiveEditorFeatures.csproj @@ -41,10 +41,6 @@ {8E2A252E-A140-45A6-A81A-2652996EA589} InteractiveFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures diff --git a/src/Interactive/EditorFeatures/Core/project.json b/src/Interactive/EditorFeatures/Core/project.json index f5d02718dc612..67d316409d811 100644 --- a/src/Interactive/EditorFeatures/Core/project.json +++ b/src/Interactive/EditorFeatures/Core/project.json @@ -1,5 +1,9 @@ { "dependencies": { + "Microsoft.VisualStudio.InteractiveWindow": { + "version": "2.0.0-beta5-60820-04", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Language.Intellisense": { "version": "14.3.25407", "suppressParent": "all" @@ -7,6 +11,10 @@ "Microsoft.VisualStudio.Editor": { "version": "14.3.25407", "suppressParent": "all" + }, + "Microsoft.VisualStudio.Language.StandardClassification": { + "version": "14.3.25407", + "suppressParent": "all" } }, "frameworks": { diff --git a/src/Interactive/EditorFeatures/VisualBasic/BasicInteractiveEditorFeatures.vbproj b/src/Interactive/EditorFeatures/VisualBasic/BasicInteractiveEditorFeatures.vbproj index e6e45e66e8877..c1e284c7ba352 100644 --- a/src/Interactive/EditorFeatures/VisualBasic/BasicInteractiveEditorFeatures.vbproj +++ b/src/Interactive/EditorFeatures/VisualBasic/BasicInteractiveEditorFeatures.vbproj @@ -19,10 +19,6 @@ {2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6} BasicCodeAnalysis - - {01e9bd68-0339-4a13-b42f-a3ca84d164f3} - InteractiveWindow - {3E7DEA65-317B-4F43-A25D-62F18D96CFD7} BasicScripting diff --git a/src/Interactive/EditorFeatures/VisualBasic/project.json b/src/Interactive/EditorFeatures/VisualBasic/project.json index 0e711c6eaecdd..e46ebc8c3daa4 100644 --- a/src/Interactive/EditorFeatures/VisualBasic/project.json +++ b/src/Interactive/EditorFeatures/VisualBasic/project.json @@ -1,5 +1,9 @@ { "dependencies": { + "Microsoft.VisualStudio.InteractiveWindow": { + "version": "2.0.0-beta5-60820-04", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Text.UI": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/InteractiveWindow/Editor/BufferBlock.cs b/src/InteractiveWindow/Editor/BufferBlock.cs deleted file mode 100644 index 978a8115272c1..0000000000000 --- a/src/InteractiveWindow/Editor/BufferBlock.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Json; -using System.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// REPL session buffer: input, output, or prompt. - /// - [DataContract] - internal struct BufferBlock - { - [DataMember(Name = "kind")] - internal readonly ReplSpanKind Kind; - - [DataMember(Name = "content")] - internal readonly string Content; - - internal BufferBlock(ReplSpanKind kind, string content) - { - Kind = kind; - Content = content; - } - - internal static string Serialize(BufferBlock[] blocks) - { - var serializer = new DataContractJsonSerializer(typeof(BufferBlock[])); - using (var stream = new MemoryStream()) - { - serializer.WriteObject(stream, blocks); - return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length); - } - } - - /// - internal static BufferBlock[] Deserialize(string str) - { - var serializer = new DataContractJsonSerializer(typeof(BufferBlock[])); - try - { - var bytes = Encoding.UTF8.GetBytes(str); - using (var stream = new MemoryStream(bytes)) - { - var obj = serializer.ReadObject(stream); - return (BufferBlock[])obj; - } - } - catch (Exception e) - { - throw new InvalidDataException(e.Message, e); - } - } - } -} diff --git a/src/InteractiveWindow/Editor/Commands/CancelExecutionCommand.cs b/src/InteractiveWindow/Editor/Commands/CancelExecutionCommand.cs deleted file mode 100644 index ebb1c77cdb0fc..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/CancelExecutionCommand.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -#if TODO -using System.ComponentModel.Composition; -using System.Reflection; -using System.Threading.Tasks; -using System.Windows.Controls; -using System.Windows.Media.Imaging; - -namespace Microsoft.VisualStudio.InteractiveWindow { - [Export(typeof(IInteractiveWindowCommand))] - internal sealed class CancelExecutionCommand : InteractiveWindowCommand { - public override Task Execute(IInteractiveWindow window, string arguments) { - window.AbortCommand(); - return ExecutionResult.Succeeded; - } - - public override string Description { - get { return "Stops execution of the current command."; } - } - - public override object ButtonContent { - get { - var image = new BitmapImage(); - image.BeginInit(); - image.StreamSource = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.VisualStudio.Resources.CancelEvaluation.gif"); - image.EndInit(); - var res = new Image(); - res.Source = image; - res.Width = res.Height = 16; - return res; - } - } - } -} -#endif \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/Commands/ClearScreenCommand.cs b/src/InteractiveWindow/Editor/Commands/ClearScreenCommand.cs deleted file mode 100644 index b2617e074c79d..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/ClearScreenCommand.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.ComponentModel.Composition; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - [Export(typeof(IInteractiveWindowCommand))] - internal sealed class ClearScreenCommand : InteractiveWindowCommand - { - public override Task Execute(IInteractiveWindow window, string arguments) - { - window.Operations.ClearView(); - return ExecutionResult.Succeeded; - } - - public override string Description - { - get { return InteractiveWindowResources.ClearScreenCommandDescription; } - } - - public override IEnumerable Names - { - get { yield return "cls"; yield return "clear"; } - } - } -} diff --git a/src/InteractiveWindow/Editor/Commands/CommandClassifier.cs b/src/InteractiveWindow/Editor/Commands/CommandClassifier.cs deleted file mode 100644 index 79cd2075d4240..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/CommandClassifier.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.Language.StandardClassification; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - internal sealed class CommandClassifier : IClassifier - { - private readonly IStandardClassificationService _registry; - private readonly IInteractiveWindowCommands _commands; - - public CommandClassifier(IStandardClassificationService registry, IInteractiveWindowCommands commands) - { - _registry = registry; - _commands = commands; - } - - public IList GetClassificationSpans(SnapshotSpan span) - { - return _commands.Classify(span).ToArray(); - } - -#pragma warning disable 67 // unused event - // This event gets raised if a non-text change would affect the classification in some way, - // for example typing /* would cause the classification to change in C# without directly - // affecting the span. - public event EventHandler ClassificationChanged; -#pragma warning restore 67 - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/Commands/CommandClassifierProvider.cs b/src/InteractiveWindow/Editor/Commands/CommandClassifierProvider.cs deleted file mode 100644 index f3ee368606869..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/CommandClassifierProvider.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Language.StandardClassification; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - [Export(typeof(IClassifierProvider))] - [ContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName)] - internal sealed class CommandClassifierProvider : IClassifierProvider - { - [Import] - public IStandardClassificationService ClassificationRegistry { get; set; } - - public IClassifier GetClassifier(ITextBuffer textBuffer) - { - var commands = textBuffer.GetInteractiveWindow().GetInteractiveCommands(); - if (commands != null) - { - return new CommandClassifier(ClassificationRegistry, commands); - } - - return null; - } - } -} diff --git a/src/InteractiveWindow/Editor/Commands/HelpCommand.cs b/src/InteractiveWindow/Editor/Commands/HelpCommand.cs deleted file mode 100644 index 04fa1969c5663..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/HelpCommand.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - [Export(typeof(IInteractiveWindowCommand))] - internal sealed class HelpReplCommand : InteractiveWindowCommand - { - internal const string CommandName = "help"; - - public override string Description - { - get { return InteractiveWindowResources.HelpCommandDescription; } - } - - public override IEnumerable Names - { - get { yield return CommandName; } - } - - public override string CommandLine - { - get { return InteractiveWindowResources.CommandNamePlaceholder; } - } - - public override Task Execute(IInteractiveWindow window, string arguments) - { - string commandName; - IInteractiveWindowCommand command; - if (!ParseArguments(window, arguments, out commandName, out command)) - { - window.ErrorOutputWriter.WriteLine(string.Format(InteractiveWindowResources.UnknownCommand, commandName)); - ReportInvalidArguments(window); - return ExecutionResult.Failed; - } - - var commands = (IInteractiveWindowCommands)window.Properties[typeof(IInteractiveWindowCommands)]; - if (command != null) - { - commands.DisplayCommandHelp(command); - } - else - { - commands.DisplayHelp(); - } - - return ExecutionResult.Succeeded; - } - - private static readonly char[] s_whitespaceChars = new[] { '\r', '\n', ' ', '\t' }; - - private bool ParseArguments(IInteractiveWindow window, string arguments, out string commandName, out IInteractiveWindowCommand command) - { - string name = arguments.Split(s_whitespaceChars)[0]; - - if (name.Length == 0) - { - command = null; - commandName = null; - return true; - } - - var commands = window.GetInteractiveCommands(); - string prefix = commands.CommandPrefix; - - // display help on a particular command: - command = commands[name]; - - if (command == null && name.StartsWith(prefix, StringComparison.Ordinal)) - { - name = name.Substring(prefix.Length); - command = commands[name]; - } - - commandName = name; - return command != null; - } - } -} diff --git a/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommand.cs b/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommand.cs deleted file mode 100644 index c47c827034b62..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommand.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Language.StandardClassification; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - /// - /// Represents a command which can be run from a REPL window. - /// - /// This interface is a MEF contract and can be implemented and exported to add commands to the REPL window. - /// - public interface IInteractiveWindowCommand - { - /// - /// Asynchronously executes the command with specified arguments and calls back the given completion when finished. - /// - /// The interactive window. - /// Command arguments. - /// The task that completes the execution. - Task Execute(IInteractiveWindow window, string arguments); - - /// - /// Gets a brief (ideally single-line) description of the REPL command which is displayed when the user asks for help. - /// - string Description - { - get; - } - - /// - /// A single line parameters listing, or null if the command doesn't take any parameters. For example, "[on|off]". - /// - string CommandLine - { - get; - } - - /// - /// Gets detailed description of the command usage. - /// - /// - /// Returns a sequence of lines. - /// - IEnumerable DetailedDescription - { - get; - } - - /// - /// Parameter name and description for parameters of the command. - /// - IEnumerable> ParametersDescription - { - get; - } - - /// - /// The name of the command. May not contain any whitespace characters. - /// - IEnumerable Names - { - get; - } - - /// - /// Provides classification for command arguments. - /// - IEnumerable ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify); - } -} diff --git a/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommands.cs b/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommands.cs deleted file mode 100644 index 8f2b8c4f8b4c5..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommands.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - /// - /// Provides handling of meta-commands in the interactive window. Instances can be - /// created using the service. - /// - public interface IInteractiveWindowCommands - { - /// - /// Checks to see if the current input is in command mode (it is prefixed with the - /// command prefix). - /// - bool InCommand - { - get; - } - - /// - /// Gets the prefix which is used for interactive window commands. - /// - string CommandPrefix { get; } - - /// - /// Attempts to execute the command and returns the execution result. - /// - /// Returns null if the current command is unrecognized. - /// - /// - Task TryExecuteCommand(); - - /// - /// Gets the registered list of commands that this IInteractiveWindowCommands was created with. - /// - /// - IEnumerable GetCommands(); - - /// - /// Gets an individual command by name. - /// - IInteractiveWindowCommand this[string name] - { - get; - } - - /// - /// Displays help into the interactive window for the specified command. - /// - void DisplayCommandHelp(IInteractiveWindowCommand command); - - /// - /// Displays usage information in the interactive window for the specified command. - /// - void DisplayCommandUsage(IInteractiveWindowCommand command, TextWriter writer, bool displayDetails); - - /// - /// Displays help for all of the available commands. - /// - void DisplayHelp(); - - /// - /// Classifies the specified command snapshot. - /// - IEnumerable Classify(SnapshotSpan span); - } -} diff --git a/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommandsFactory.cs b/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommandsFactory.cs deleted file mode 100644 index 4978f212bea0b..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/IInteractiveWindowCommandsFactory.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - /// - /// Creates an which handles updating the context type for the command type, - /// classification of commands, and execution of commands. - /// - /// - /// Engines need to use this interface to respond to checks if code can be executed and to - /// execute text when in a command mode. - /// - /// The commands that are available for this interactive window are provided at creation time - /// along with the prefix which commands should be prefaced with. - /// - public interface IInteractiveWindowCommandsFactory - { - /// - /// Creates the IInteractiveCommands instance. - /// - IInteractiveWindowCommands CreateInteractiveCommands(IInteractiveWindow window, string prefix, IEnumerable commands); - } -} diff --git a/src/InteractiveWindow/Editor/Commands/InteractiveCommandsFactory.cs b/src/InteractiveWindow/Editor/Commands/InteractiveCommandsFactory.cs deleted file mode 100644 index 64c1af96de298..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/InteractiveCommandsFactory.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Language.StandardClassification; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - [Export(typeof(IInteractiveWindowCommandsFactory))] - internal class InteractiveCommandsFactory : IInteractiveWindowCommandsFactory - { - private readonly IContentTypeRegistryService _contentTypeRegistry; - private readonly IStandardClassificationService _standardClassification; - - [ImportingConstructor] - public InteractiveCommandsFactory(IContentTypeRegistryService contentTypeRegistry, IStandardClassificationService classification) - { - _contentTypeRegistry = contentTypeRegistry; - _standardClassification = classification; - } - - public IInteractiveWindowCommands CreateInteractiveCommands(IInteractiveWindow window, string prefix, IEnumerable commands) - { - return new Commands(window, prefix, commands.ToArray(), _contentTypeRegistry, _standardClassification); - } - } -} diff --git a/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommand.cs b/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommand.cs deleted file mode 100644 index 1d2a95e2bd677..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommand.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - /// - /// Represents a command which can be run from a REPL window. - /// - /// This interface is a MEF contract and can be implemented and exported to add commands to the REPL window. - /// - [ContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName)] - internal abstract class InteractiveWindowCommand : IInteractiveWindowCommand - { - public abstract Task Execute(IInteractiveWindow window, string arguments); - - public abstract string Description { get; } - - public abstract IEnumerable Names { get; } - - public virtual IEnumerable ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify) - { - return Enumerable.Empty(); - } - - public virtual string CommandLine - { - get { return null; } - } - - public virtual IEnumerable DetailedDescription - { - get { return null; } - } - - public virtual IEnumerable> ParametersDescription - { - get { return null; } - } - - protected void ReportInvalidArguments(IInteractiveWindow window) - { - var commands = (IInteractiveWindowCommands)window.Properties[typeof(IInteractiveWindowCommands)]; - commands.DisplayCommandUsage(this, window.ErrorOutputWriter, displayDetails: false); - } - } -} diff --git a/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommandExtensions.cs b/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommandExtensions.cs deleted file mode 100644 index 431fc4e96f5a8..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommandExtensions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - public static class InteractiveWindowCommandExtensions - { - /// - /// Gets the IInteractiveWindowCommands instance for the current interactive window if one is defined. - /// - /// Returns null if the interactive commands have not been created for this window. - /// - public static IInteractiveWindowCommands GetInteractiveCommands(this IInteractiveWindow window) - { - IInteractiveWindowCommands commands; - if (window.Properties.TryGetProperty(typeof(IInteractiveWindowCommands), out commands)) - { - return commands; - } - - return null; - } - } -} diff --git a/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommands.cs b/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommands.cs deleted file mode 100644 index adc5d1d9ecd02..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/InteractiveWindowCommands.cs +++ /dev/null @@ -1,379 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Language.StandardClassification; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - internal sealed class Commands : IInteractiveWindowCommands - { - private const string _commandSeparator = ", "; - - private readonly Dictionary _commands; - private readonly int _maxCommandNameLength; - private readonly IInteractiveWindow _window; - private readonly IContentType _commandContentType; - private readonly IStandardClassificationService _classificationRegistry; - private IContentType _languageContentType; - private ITextBuffer _previousBuffer; - - public string CommandPrefix { get; set; } - - public bool InCommand - { - get - { - return _window.CurrentLanguageBuffer.ContentType == _commandContentType; - } - } - - internal Commands(IInteractiveWindow window, string prefix, IEnumerable commands, IContentTypeRegistryService contentTypeRegistry = null, IStandardClassificationService classificationRegistry = null) - { - CommandPrefix = prefix; - _window = window; - - Dictionary commandsDict = new Dictionary(); - foreach (var command in commands) - { - int length = 0; - foreach (var name in command.Names) - { - if (commandsDict.ContainsKey(name)) - { - throw new InvalidOperationException(string.Format(InteractiveWindowResources.DuplicateCommand, string.Join(_commandSeparator, command.Names))); - } - if (length != 0) - { - length += _commandSeparator.Length; - } - // plus the length of `#` for display purpose - length += name.Length + 1; - - commandsDict[name] = command; - } - if (length == 0) - { - throw new InvalidOperationException(string.Format(InteractiveWindowResources.MissingCommandName, command.GetType().Name)); - } - _maxCommandNameLength = Math.Max(_maxCommandNameLength, length); - } - - _commands = commandsDict; - - _classificationRegistry = classificationRegistry; - - if (contentTypeRegistry != null) - { - _commandContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); - } - - if (window != null) - { - window.SubmissionBufferAdded += Window_SubmissionBufferAdded; - window.Properties[typeof(IInteractiveWindowCommands)] = this; - } - } - - private void Window_SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e) - { - if (_previousBuffer != null) - { - _previousBuffer.Changed -= NewBufferChanged; - } - - _languageContentType = e.NewBuffer.ContentType; - e.NewBuffer.Changed += NewBufferChanged; - _previousBuffer = e.NewBuffer; - } - - private void NewBufferChanged(object sender, TextContentChangedEventArgs e) - { - bool isCommand = IsCommand(e.After.GetExtent()); - - ITextBuffer buffer = e.After.TextBuffer; - IContentType contentType = buffer.ContentType; - IContentType newContentType = null; - - if (contentType == _languageContentType) - { - if (isCommand) - { - newContentType = _commandContentType; - } - } - else - { - if (!isCommand) - { - newContentType = _languageContentType; - } - } - - if (newContentType != null) - { - buffer.ChangeContentType(newContentType, editTag: null); - } - } - - internal bool IsCommand(SnapshotSpan span) - { - SnapshotSpan prefixSpan, commandSpan, argumentsSpan; - return TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan) != null; - } - - internal IInteractiveWindowCommand TryParseCommand(SnapshotSpan span, out SnapshotSpan prefixSpan, out SnapshotSpan commandSpan, out SnapshotSpan argumentsSpan) - { - string prefix = CommandPrefix; - - SnapshotSpan trimmed = span.TrimStart(); - if (!trimmed.StartsWith(prefix)) - { - prefixSpan = commandSpan = argumentsSpan = default(SnapshotSpan); - return null; - } - - prefixSpan = trimmed.SubSpan(0, prefix.Length); - var nameAndArgs = trimmed.SubSpan(prefix.Length).TrimStart(); - SnapshotPoint nameEnd = nameAndArgs.IndexOfAnyWhiteSpace() ?? span.End; - commandSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameAndArgs.Start.Position, nameEnd.Position)); - - argumentsSpan = new SnapshotSpan(span.Snapshot, Span.FromBounds(nameEnd.Position, span.End.Position)).Trim(); - - return this[commandSpan.GetText()]; - } - - public IInteractiveWindowCommand this[string name] - { - get - { - IInteractiveWindowCommand command; - _commands.TryGetValue(name, out command); - return command; - } - } - - public IEnumerable GetCommands() - { - return _commands.Values; - } - - internal IEnumerable Help() - { - // The magic number `19` here is calculated based on how the description is dispayed for other help entries to keep the texts aligned - // (As of now other help entries include REPL commands and script derectives, both have manually formatted help description strings. - string format = "{0,-" + Math.Max(19, _maxCommandNameLength) + "} {1}"; - return _commands.GroupBy(entry => entry.Value). - Select(group => string.Format(format, string.Join(_commandSeparator, group.Key.Names.Select(s => CommandPrefix + s)), group.Key.Description)). - OrderBy(line => line); - } - - public IEnumerable Classify(SnapshotSpan span) - { - SnapshotSpan prefixSpan, commandSpan, argumentsSpan; - var command = TryParseCommand(span.Snapshot.GetExtent(), out prefixSpan, out commandSpan, out argumentsSpan); - if (command == null) - { - yield break; - } - - if (span.OverlapsWith(prefixSpan)) - { - yield return Classification(span.Snapshot, prefixSpan, _classificationRegistry.Keyword); - } - - if (span.OverlapsWith(commandSpan)) - { - yield return Classification(span.Snapshot, commandSpan, _classificationRegistry.Keyword); - } - - if (argumentsSpan.Length > 0) - { - foreach (var classifiedSpan in command.ClassifyArguments(span.Snapshot, argumentsSpan.Span, span.Span)) - { - yield return classifiedSpan; - } - } - } - - private ClassificationSpan Classification(ITextSnapshot snapshot, Span span, IClassificationType classificationType) - { - return new ClassificationSpan(new SnapshotSpan(snapshot, span), classificationType); - } - - /// - /// Null if parsing fails, the result of execution otherwise. - /// - public Task TryExecuteCommand() - { - var span = _window.CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); - - SnapshotSpan prefixSpan, commandSpan, argumentsSpan; - var command = TryParseCommand(span, out prefixSpan, out commandSpan, out argumentsSpan); - if (command == null) - { - return null; - } - - return ExecuteCommandAsync(command, argumentsSpan.GetText()); - } - - private async Task ExecuteCommandAsync(IInteractiveWindowCommand command, string arguments) - { - try - { - return await command.Execute(_window, arguments).ConfigureAwait(false); - } - catch (Exception e) - { - _window.ErrorOutputWriter.WriteLine(InteractiveWindowResources.CommandFailed, command.Names.First(), e.Message); - return ExecutionResult.Failure; - } - } - - private const string HelpIndent = " "; - - private static readonly string[] s_CSVBScriptDirectives = new[] - { - "#r " + InteractiveWindowResources.RefHelp, - "#load " + InteractiveWindowResources.LoadHelp - }; - - private static readonly string[] s_shortcutDescriptions = new[] - { - "Enter " + InteractiveWindowResources.EnterHelp, - "Ctrl-Enter " + InteractiveWindowResources.CtrlEnterHelp1, - " " + InteractiveWindowResources.CtrlEnterHelp2, - "Shift-Enter " + InteractiveWindowResources.ShiftEnterHelp, - "Escape " + InteractiveWindowResources.EscapeHelp, - "Alt-UpArrow " + InteractiveWindowResources.AltUpArrowHelp, - "Alt-DownArrow " + InteractiveWindowResources.AltDownArrowHelp, - "Ctrl-Alt-UpArrow " + InteractiveWindowResources.CtrlAltUpArrowHelp, - "Ctrl-Alt-DownArrow " + InteractiveWindowResources.CtrlAltDownArrowHelp, - "Ctrl-K, Ctrl-Enter " + InteractiveWindowResources.CtrlKCtrlEnterHelp, - "Ctrl-E, Ctrl-Enter " + InteractiveWindowResources.CtrlECtrlEnterHelp, - "Ctrl-A " + InteractiveWindowResources.CtrlAHelp - }; - - private static readonly string[] s_shortcutDescriptionsSmartUpDown = new[] - { - "UpArrow " + InteractiveWindowResources.UpArrowHelp1, - " " + InteractiveWindowResources.UpArrowHelp2, - "DownArrow " + InteractiveWindowResources.DownArrowHelp1, - " " + InteractiveWindowResources.DownArrowHelp2 - }; - - - internal string ShortcutDescriptions - { - get - { - var sb = new StringBuilder(); - foreach (var line in s_shortcutDescriptions) - { - sb.Append(HelpIndent + line + "\r\n"); - } - if (UseSmartUpDown) - { - foreach (var line in s_shortcutDescriptionsSmartUpDown) - { - sb.Append(HelpIndent + line + "\r\n"); - } - } - return sb.ToString(); - } - } - - public void DisplayHelp() - { - _window.WriteLine(InteractiveWindowResources.KeyboardShortcuts); - _window.Write(ShortcutDescriptions); - - _window.WriteLine(InteractiveWindowResources.ReplCommands); - foreach (var line in Help()) - { - _window.Write(HelpIndent); - _window.WriteLine(line); - } - - // Hack: Display script directives only in CS/VB interactive window - // TODO: https://github.com/dotnet/roslyn/issues/6441 - var evaluatorTypeName = _window.Evaluator.GetType().Name; - if (evaluatorTypeName == "CSharpInteractiveEvaluator" || - evaluatorTypeName == "VisualBasicInteractiveEvaluator") - { - _window.WriteLine(InteractiveWindowResources.CSVBScriptDirectives); - foreach (var line in s_CSVBScriptDirectives) - { - _window.Write(HelpIndent); - _window.WriteLine(line); - } - } - } - - public void DisplayCommandUsage(IInteractiveWindowCommand command, TextWriter writer, bool displayDetails) - { - if (displayDetails) - { - writer.WriteLine(command.Description); - writer.WriteLine(string.Empty); - } - - writer.WriteLine(InteractiveWindowResources.Usage); - writer.Write(HelpIndent); - writer.Write(CommandPrefix); - writer.Write(string.Join(_commandSeparator + CommandPrefix, command.Names)); - - string commandLine = command.CommandLine; - if (commandLine != null) - { - writer.Write(" "); - writer.Write(commandLine); - } - - if (displayDetails) - { - writer.WriteLine(string.Empty); - - var paramsDesc = command.ParametersDescription; - if (paramsDesc != null && paramsDesc.Any()) - { - writer.WriteLine(string.Empty); - writer.WriteLine(InteractiveWindowResources.Parameters); - - int maxParamNameLength = paramsDesc.Max(entry => entry.Key.Length); - string paramHelpLineFormat = HelpIndent + "{0,-" + maxParamNameLength + "} {1}"; - - foreach (var paramDesc in paramsDesc) - { - writer.WriteLine(string.Format(paramHelpLineFormat, paramDesc.Key, paramDesc.Value)); - } - } - - IEnumerable details = command.DetailedDescription; - if (details != null && details.Any()) - { - writer.WriteLine(string.Empty); - foreach (var line in details) - { - writer.WriteLine(line); - } - } - } - } - - public void DisplayCommandHelp(IInteractiveWindowCommand command) - { - DisplayCommandUsage(command, _window.OutputWriter, displayDetails: true); - } - - private bool UseSmartUpDown => _window.TextView.Options.GetOptionValue(InteractiveWindowOptions.SmartUpDown); - } -} diff --git a/src/InteractiveWindow/Editor/Commands/PredefinedInteractiveCommandsContentTypes.cs b/src/InteractiveWindow/Editor/Commands/PredefinedInteractiveCommandsContentTypes.cs deleted file mode 100644 index 6f9a07a5ee29a..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/PredefinedInteractiveCommandsContentTypes.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Utilities; - -#pragma warning disable CS0649 // field is not assigned to - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - public static class PredefinedInteractiveCommandsContentTypes - { - public const string InteractiveCommandContentTypeName = "Interactive Command"; - - [Export, Name(InteractiveCommandContentTypeName), BaseDefinition("code")] - internal static readonly ContentTypeDefinition InteractiveCommandContentTypeDefinition; - } -} diff --git a/src/InteractiveWindow/Editor/Commands/ResetCommand.cs b/src/InteractiveWindow/Editor/Commands/ResetCommand.cs deleted file mode 100644 index 9f8f3bad27747..0000000000000 --- a/src/InteractiveWindow/Editor/Commands/ResetCommand.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel.Composition; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Language.StandardClassification; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; - -namespace Microsoft.VisualStudio.InteractiveWindow.Commands -{ - [Export(typeof(IInteractiveWindowCommand))] - internal sealed class ResetCommand : InteractiveWindowCommand - { - private const string CommandName = "reset"; - private const string NoConfigParameterName = "noconfig"; - private static readonly int s_noConfigParameterNameLength = NoConfigParameterName.Length; - private readonly IStandardClassificationService _registry; - - [ImportingConstructor] - public ResetCommand(IStandardClassificationService registry) - { - _registry = registry; - } - - public override string Description - { - get { return InteractiveWindowResources.ResetCommandDescription; } - } - - public override IEnumerable Names - { - get { yield return CommandName; } - } - - public override string CommandLine - { - get { return "[" + NoConfigParameterName + "]"; } - } - - public override IEnumerable> ParametersDescription - { - get - { - yield return new KeyValuePair(NoConfigParameterName, InteractiveWindowResources.ResetCommandParametersDescription); - } - } - - public override Task Execute(IInteractiveWindow window, string arguments) - { - bool initialize; - if (!TryParseArguments(arguments, out initialize)) - { - ReportInvalidArguments(window); - return ExecutionResult.Failed; - } - - return window.Operations.ResetAsync(initialize); - } - - public override IEnumerable ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify) - { - string arguments = snapshot.GetText(argumentsSpan); - int argumentsStart = argumentsSpan.Start; - foreach (var pos in GetNoConfigPositions(arguments)) - { - var snapshotSpan = new SnapshotSpan(snapshot, new Span(argumentsStart + pos, s_noConfigParameterNameLength)); - yield return new ClassificationSpan(snapshotSpan, _registry.Keyword); - } - } - - /// - /// Internal for testing. - /// - internal static IEnumerable GetNoConfigPositions(string arguments) - { - int startIndex = 0; - while (true) - { - int index = arguments.IndexOf(NoConfigParameterName, startIndex, StringComparison.Ordinal); - if (index < 0) yield break; - - if ((index == 0 || char.IsWhiteSpace(arguments[index - 1])) && - (index + s_noConfigParameterNameLength == arguments.Length || char.IsWhiteSpace(arguments[index + s_noConfigParameterNameLength]))) - { - yield return index; - } - - startIndex = index + s_noConfigParameterNameLength; - } - } - - /// - /// Internal for testing. - /// - internal static bool TryParseArguments(string arguments, out bool initialize) - { - var trimmed = arguments.Trim(); - if (trimmed.Length == 0) - { - initialize = true; - return true; - } - else if (string.Equals(trimmed, NoConfigParameterName, StringComparison.Ordinal)) - { - initialize = false; - return true; - } - - initialize = false; - return false; - } - } -} diff --git a/src/InteractiveWindow/Editor/ContentTypeMetadata.cs b/src/InteractiveWindow/Editor/ContentTypeMetadata.cs deleted file mode 100644 index 7f6b69d09df0b..0000000000000 --- a/src/InteractiveWindow/Editor/ContentTypeMetadata.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal class ContentTypeMetadata - { - public IEnumerable ContentTypes { get; } - - public ContentTypeMetadata(IDictionary data) - { - this.ContentTypes = (IEnumerable)data["ContentTypes"]; - } - } - - internal static class ContentTypeMetadataHelpers - { - public static T OfContentType( - this IEnumerable> exports, - IContentType contentType, - IContentTypeRegistryService contentTypeRegistry) - { - return (from export in exports - from exportedContentTypeName in export.Metadata.ContentTypes - let exportedContentType = contentTypeRegistry.GetContentType(exportedContentTypeName) - where exportedContentType.IsOfType(contentType.TypeName) - select export.Value).SingleOrDefault(); - } - } -} diff --git a/src/InteractiveWindow/Editor/CustomTrackingSpan.cs b/src/InteractiveWindow/Editor/CustomTrackingSpan.cs deleted file mode 100644 index 94d9f85a904aa..0000000000000 --- a/src/InteractiveWindow/Editor/CustomTrackingSpan.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Diagnostics; -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// This is a custom span which is like an EdgeInclusive span. We need a custom span because elision buffers - /// do not allow EdgeInclusive unless it spans the entire buffer. We create snippets of our language spans - /// and these are initially zero length. When we insert at the beginning of these we'll end up keeping the - /// span zero length if we're just EdgePositive tracking. - /// - [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] - internal sealed class CustomTrackingSpan : ITrackingSpan - { - private readonly ITrackingPoint _start; - private readonly ITrackingPoint _end; - - public CustomTrackingSpan(ITextSnapshot snapshot, Span span, bool canAppend = false) - { - _start = snapshot.CreateTrackingPoint(span.Start, PointTrackingMode.Negative); - _end = snapshot.CreateTrackingPoint(span.End, canAppend ? PointTrackingMode.Positive : PointTrackingMode.Negative); - } - - #region ITrackingSpan Members - - public SnapshotPoint GetEndPoint(ITextSnapshot snapshot) - { - return _end.GetPoint(snapshot); - } - - public Span GetSpan(ITextVersion version) - { - return Span.FromBounds(_start.GetPosition(version), _end.GetPosition(version)); - } - - public SnapshotSpan GetSpan(ITextSnapshot snapshot) - { - return new SnapshotSpan(snapshot, Span.FromBounds(_start.GetPoint(snapshot), _end.GetPoint(snapshot))); - } - - public SnapshotPoint GetStartPoint(ITextSnapshot snapshot) - { - return _start.GetPoint(snapshot); - } - - public string GetText(ITextSnapshot snapshot) - { - return GetSpan(snapshot).GetText(); - } - - public ITextBuffer TextBuffer - { - get { return _start.TextBuffer; } - } - - public TrackingFidelityMode TrackingFidelity - { - get { return TrackingFidelityMode.Forward; } - } - - public SpanTrackingMode TrackingMode - { - get { return SpanTrackingMode.Custom; } - } - - #endregion - - private string GetDebuggerDisplay() - { - return "CustomSpan: " + GetSpan(_start.TextBuffer.CurrentSnapshot).ToString(); - } - } -} diff --git a/src/InteractiveWindow/Editor/ExecutionResult.cs b/src/InteractiveWindow/Editor/ExecutionResult.cs deleted file mode 100644 index 5cfbd66e3c8ee..0000000000000 --- a/src/InteractiveWindow/Editor/ExecutionResult.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// The result of command execution. - /// - public struct ExecutionResult - { - public static readonly ExecutionResult Success = new ExecutionResult(true); - public static readonly ExecutionResult Failure = new ExecutionResult(false); - public static readonly Task Succeeded = Task.FromResult(Success); - public static readonly Task Failed = Task.FromResult(Failure); - - private readonly bool _isSuccessful; - - public ExecutionResult(bool isSuccessful) - { - _isSuccessful = isSuccessful; - } - - public bool IsSuccessful - { - get - { - return _isSuccessful; - } - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/History.cs b/src/InteractiveWindow/Editor/History.cs deleted file mode 100644 index 6c1c5ef959bce..0000000000000 --- a/src/InteractiveWindow/Editor/History.cs +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal class History - { - internal sealed class Entry - { - /// - /// The cached text of this entry, which may exist if we've detached from the span. - /// - private string _cachedText; - - /// - /// The span of the original submission of this text. - /// - private SnapshotSpan? _originalSpan; - - public bool Command { get; set; } - public bool Failed { get; set; } - - public SnapshotSpan? OriginalSpan { get { return _originalSpan; } } - - public string Text - { - get - { - if (_cachedText != null) - { - return _cachedText; - } - - return _originalSpan.Value.GetText(); - } - } - - internal void ForgetOriginalBuffer() - { - if (_originalSpan.HasValue) - { - _cachedText = _originalSpan.Value.GetText(); - _originalSpan = null; - } - } - - public Entry(SnapshotSpan span) - { - _originalSpan = span; - } - } - - private readonly List _history; - private readonly int _maxLength; - - private int _current; - private bool _live; - - internal string UncommittedInput { get; set; } - - internal History() - : this(maxLength: 50) - { - } - - internal History(int maxLength) - { - _maxLength = maxLength; - _current = -1; - _history = new List(); - } - - internal void Clear() - { - _current = -1; - _live = false; - _history.Clear(); - } - - internal void ForgetOriginalBuffers() - { - foreach (var entry in _history) - { - entry.ForgetOriginalBuffer(); - } - } - - internal int MaxLength - { - get { return _maxLength; } - } - - internal int Length - { - get { return _history.Count; } - } - - internal IEnumerable Items - { - get { return _history; } - } - - internal Entry Last - { - get - { - if (_history.Count > 0) - { - return _history[_history.Count - 1]; - } - else - { - return null; - } - } - } - - internal void Add(SnapshotSpan span) - { - var entry = new Entry(span); - var text = span.GetText(); - - _live = false; - if (Length == 0 || Last.Text != text) - { - _history.Add(entry); - } - - //If text at current location in history is not the same as the text you are adding then - //new command was typed and submitted while navigating history. In this case the _current - //gets reset. - if (_history[(_current == -1) ? Length - 1 : _current].Text != text) - { - _current = -1; - } - - if (Length > MaxLength) - { - _history.RemoveAt(0); - if (_current > 0) - { - _current--; - } - } - } - - internal Entry GetNext(string pattern) - { - var next = MoveNext(pattern); - if (next == null) - { - // if we hit the end of history list, reset _current to stop navigating history. - _current = -1; - } - return next; - } - - internal Entry GetPrevious(string pattern) - { - var startPos = _current; - Entry next; - next = MovePrevious(pattern); - if (next == null) - { - _current = startPos; - return null; - } - - return next; - } - - private Entry MoveNext(string pattern) - { - if (Length == 0) return null; - - bool wasCurrentUninitialized = (_current == -1); - - // if current in un-initialized then we are not navigating history yet so - // there is no next entry. - if (wasCurrentUninitialized) return null; - - //indicates that history search/navigation is in progress - _live = true; - - _current++; - - for (; _current < Length; _current++) - { - Entry entry; - if (TryMatch(pattern, out entry)) return entry; - } - - return null; - } - - private Entry MovePrevious(string pattern) - { - if (Length == 0) return null; - bool wasLive = _live; - - //indicates that history search/navigation is in progress - _live = true; - - bool wasCurrentUninitialized = (_current == -1); - - // if current in un-initialized then we are not navigating history yet so - // current needs to be set to last entry before navigating previous. - if (wasCurrentUninitialized) - { - _current = Length - 1; - Entry entry; - if (TryMatch(pattern, out entry)) return entry; - } - - bool patternEmpty = string.IsNullOrWhiteSpace(pattern); - if (!wasLive && patternEmpty) - { - //return the current entry again ( handles case up, up, enter, up) - Entry entry; - if (TryMatch(pattern, out entry)) return entry; - } - - for (_current--; _current >= 0; _current--) - { - Entry entry; - if (TryMatch(pattern, out entry)) return entry; - } - - return null; - } - - - private bool TryMatch(string pattern, out Entry entry) - { - bool patternEmpty = string.IsNullOrWhiteSpace(pattern); - var tmpEntry = _history[_current]; - if (patternEmpty || Matches(tmpEntry.Text, pattern)) - { - entry = tmpEntry; - return true; - } - else - { - entry = null; - return false; - } - } - - private static bool Matches(string entry, string pattern) - { - return entry.Contains(pattern); - } - } -} diff --git a/src/InteractiveWindow/Editor/IInteractiveEvaluator.cs b/src/InteractiveWindow/Editor/IInteractiveEvaluator.cs deleted file mode 100644 index 8fea40a02d864..0000000000000 --- a/src/InteractiveWindow/Editor/IInteractiveEvaluator.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// Implements an evaluator for a specific REPL implementation. The evaluator is provided to the - /// REPL implementation by the IInteractiveEngineProvider interface. - /// - public interface IInteractiveEvaluator : IDisposable - { - /// - /// Gets or sets Interactive Window the engine is currently attached to. - /// - IInteractiveWindow CurrentWindow { get; set; } - - /// - /// Initializes the interactive session. - /// - /// Task that completes the initialization. - Task InitializeAsync(); - - /// - /// Re-starts the interpreter. Usually this closes the current process (if alive) and starts - /// a new interpreter. - /// - /// Task that completes reset and initialization of the new process. - Task ResetAsync(bool initialize = true); - - // Parsing and Execution - - /// - /// Returns true if the text can be executed. Used to determine if there is a whole statement entered - /// in the REPL window. - /// - bool CanExecuteCode(string text); - - /// - /// Asynchronously executes the specified text. - /// - /// The code snippet to execute. - /// Task that completes the execution. - Task ExecuteCodeAsync(string text); - - /// - /// Formats the contents of the clipboard in a manner reasonable for the language. Returns null if the - /// current clipboard cannot be formatted. - /// - /// - /// - /// By default if the clipboard contains text it will be pasted. The language can format - /// additional forms here - for example CSV data can be formatted in a language compatible - /// manner. - /// - string FormatClipboard(); - - /// - /// Aborts the current running command. - /// - void AbortExecution(); - - /// - /// Retrieves the prompt string. - /// - /// The prompt string. - string GetPrompt(); - } -} diff --git a/src/InteractiveWindow/Editor/IInteractiveWindow.cs b/src/InteractiveWindow/Editor/IInteractiveWindow.cs deleted file mode 100644 index 6d01ad224e5e9..0000000000000 --- a/src/InteractiveWindow/Editor/IInteractiveWindow.cs +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using System.Windows; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Operations; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// An implementation of a Read Eval Print Loop Window for iteratively developing code. - /// - /// Instances of the repl window can be created by using MEF to import the IInteractiveWindowProvider interface. - /// - public interface IInteractiveWindow : IDisposable, IPropertyOwner - { - /// - /// Gets the text view which the interactive window is running and writing output to. - /// - IWpfTextView TextView - { - get; - } - - /// - /// Gets the current language buffer. - /// - ITextBuffer CurrentLanguageBuffer - { - get; - } - - /// - /// Gets the output editor buffer. - /// - ITextBuffer OutputBuffer - { - get; - } - - /// - /// The language evaluator used in Repl Window - /// - IInteractiveEvaluator Evaluator - { - get; - } - - /// - /// Initializes the execution environment and shows the initial prompt. - /// - /// Returns a started task that finishes as soon as the initialization completes. - Task InitializeAsync(); - - /// - /// Closes the underlying text view. - /// - void Close(); - - /// - /// Insert the specified text to the active code buffer at the current caret position. - /// - /// Text to insert. - /// - /// Overwrites the current selection. - /// - /// If the REPL is in the middle of code execution the text is inserted at the end of a pending input buffer. - /// When the REPL is ready for input the pending input is inserted into the active code input. - /// - void InsertCode(string text); - - /// - /// Submits a sequence of inputs one by one. - /// - /// - /// Code snippets or REPL commands to submit. - /// - /// - /// Enqueues given code snippets for submission at the earliest time the REPL is prepared to - /// accept submissions. Any submissions are postponed until execution of the current - /// submission (if there is any) is finished or aborted. - /// - /// The REPL processes the given inputs one by one creating a prompt, input span and possibly output span for each input. - /// This method may be reentered if any of the inputs evaluates to a command that invokes this method. - /// - Task SubmitAsync(IEnumerable inputs); - - /// - /// Output writer. - /// - /// REVIEW: Remove, other people can wrap Write APIS - /// - TextWriter OutputWriter - { - get; - } - - /// - /// Error output writer. - /// - /// REVIEW: Remove, other people can wrap Write APIS - /// - TextWriter ErrorOutputWriter - { - get; - } - - /// - /// Writes string followed by a line break into the output buffer. - /// - /// Text to write. Might be null. - /// - /// The offset in the output subject buffer where the text is inserted and the length of the inserted text including the line break. - /// - /// - /// Note that the text might not be written to the editor buffer immediately but be buffered. - /// The returned offsets might thus be beyond the current length of the editor buffer. - /// - Span WriteLine(string text); - - /// - /// Writes a line into the output buffer. - /// - /// Text to write. Might be null. - /// - /// The offset in the output subject buffer where the text is inserted. - /// - /// - /// Note that the text might not be written to the editor buffer immediately but be buffered. - /// The returned offset might thus be beyond the current length of the editor buffer. - /// - Span Write(string text); - - /// - /// Writes string followed by a line break into the error buffer. - /// - /// Text to write. Might be null. - /// - /// The offset in the output subject buffer where the text is inserted and the length of the inserted text including the line break. - /// - /// - /// Note that the text might not be written to the editor buffer immediately but be buffered. - /// The returned offsets might thus be beyond the current length of the editor buffer. - /// - Span WriteErrorLine(string text); - - /// - /// Writes a line into the error buffer. - /// - /// Text to write. Might be null. - /// - /// The offset in the output subject buffer where the text is inserted. - /// - /// - /// Note that the text might not be written to the editor buffer immediately but be buffered. - /// The returned offset might thus be beyond the current length of the editor buffer. - /// - Span WriteError(string text); - - /// - /// Writes a UI object to the REPL window. - /// - /// - /// Flushes all text previously written to the output buffer before the element is inserted. - /// - void Write(UIElement element); - - void FlushOutput(); - - /// - /// Reads input from the REPL window. - /// - /// The entered input or null if cancelled. - TextReader ReadStandardInput(); - - /// - /// Event triggered when the REPL is ready to accept input. - /// - /// - /// Called on the UI thread. - /// - event Action ReadyForInput; - - event EventHandler SubmissionBufferAdded; - - /// - /// True if there is currently an input being executed. - /// - /// - /// - /// This value can only be reliably queried on the UI thread, otherwise the value - /// is transient. - /// - bool IsRunning - { - get; - } - - /// - /// True if the interactive evaluator is currently resetting. - /// - /// - /// - /// This value can only be reliably queried on the UI thread, otherwise the value - /// is transient. - /// - bool IsResetting - { - get; - } - - /// - /// True if the interactive evaluator is currently resetting. - /// - /// - /// - /// This value can only be reliably queried on the UI thread, otherwise the value - /// is transient. - /// - bool IsInitializing - { - get; - } - - /// - /// Appends a input into the editor buffer and history as if it has been executed. - /// - /// The input is not executed. - /// - void AddInput(string input); - - IInteractiveWindowOperations Operations - { - get; - } - } -} diff --git a/src/InteractiveWindow/Editor/IInteractiveWindow2.cs b/src/InteractiveWindow/Editor/IInteractiveWindow2.cs deleted file mode 100644 index 3376971ac1844..0000000000000 --- a/src/InteractiveWindow/Editor/IInteractiveWindow2.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - public interface IInteractiveWindow2 : IInteractiveWindow - { - /// - /// Adds to the history as if it has been executed. - /// Method doesn't execute and doesn't affect current user input. - /// - /// The interactive window has not been initialized or is resettings. - void AddToHistory(string input); - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/IInteractiveWindowEditorFactoryService.cs b/src/InteractiveWindow/Editor/IInteractiveWindowEditorFactoryService.cs deleted file mode 100644 index 1f0d10027552a..0000000000000 --- a/src/InteractiveWindow/Editor/IInteractiveWindowEditorFactoryService.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Projection; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// Implements the service that creates text views and buffers for the interactive window. - /// - /// There is a single implementation of this service for each MEF composition catalog. The - /// service understands how the editors and buffers need to be created and sets them up - /// so that commands are properly routed to the editor window. - /// - /// This service is imported by - /// to use in the creation of s. - /// - public interface IInteractiveWindowEditorFactoryService - { - /// - /// Creates a new text view for an interactive window. - /// - /// The interactive window the text view is being created for. - /// The projection buffer used for displaying the interactive window - /// The requested text view roles. - IWpfTextView CreateTextView(IInteractiveWindow window, ITextBuffer buffer, ITextViewRoleSet roles); - - /// - /// Creates a new input buffer for the interactive window. - /// - ITextBuffer CreateAndActivateBuffer(IInteractiveWindow window); - } -} diff --git a/src/InteractiveWindow/Editor/IInteractiveWindowFactoryService.cs b/src/InteractiveWindow/Editor/IInteractiveWindowFactoryService.cs deleted file mode 100644 index 6ecf424625c27..0000000000000 --- a/src/InteractiveWindow/Editor/IInteractiveWindowFactoryService.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// Creates instances of the IInteractiveWindow. - /// - public interface IInteractiveWindowFactoryService - { - /// - /// Creates a new interactive window which runs against the provided interactive evaluator. - /// - IInteractiveWindow CreateWindow(IInteractiveEvaluator evaluator); - } -} diff --git a/src/InteractiveWindow/Editor/IInteractiveWindowOperations.cs b/src/InteractiveWindow/Editor/IInteractiveWindowOperations.cs deleted file mode 100644 index 2b4b551f520c4..0000000000000 --- a/src/InteractiveWindow/Editor/IInteractiveWindowOperations.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// Provides access to low level editor operations on the REPL window. - /// - public interface IInteractiveWindowOperations - { - /// - /// Deletes the current selection or the character before the caret. - /// - /// - bool Backspace(); - - /// - /// Attempts to insert a line break. Returns true if a line break is inserted, false if not. - /// - /// Will not submit the input. - /// - bool BreakLine(); - - /// - /// Clears the input history. - /// - void ClearHistory(); - - /// - /// Clears the REPL window screen. - /// - void ClearView(); - - /// - /// Advances to the next item in history. - /// - void HistoryNext(string search = null); - - /// - /// Advanced to the previous item in history. - /// - void HistoryPrevious(string search = null); - - /// - /// If no search has been performed captures the current input as - /// the search string. Then searches through history for the next - /// match against the current search string. - /// - void HistorySearchNext(); - - /// - /// If no search has been performed captures the current input as - /// the search string. Then searches through history for the previous - /// match against the current search string. - /// - void HistorySearchPrevious(); - - /// - /// Moves to the beginning of the line. - /// - /// When in a language buffer the caret is moved to the beginning of the - /// input region not into the prompt region. - /// - /// The caret is moved to the first non-whitespace character. - /// - /// True to extend the selection from the current caret position. - void Home(bool extendSelection); - - /// - /// Moves to the end of the line. - /// - /// True to extend the selection from the current caret position. - void End(bool extendSelection); - - /// - /// Selects all of the text in the buffer - /// - void SelectAll(); - - /// - /// Pastes the current clipboard contents into the interactive window. - /// - /// - bool Paste(); - - /// - /// Cuts the current selection to the clipboard. - /// - void Cut(); - - /// - /// Deletes the current selection. - /// - /// Returns true if the selection was deleted - /// - bool Delete(); - - /// - /// Handles the user pressing return/enter. - /// - /// If the caret is at the end of an input submits the current input. Otherwise if the caret is - /// in a language buffer it inserts a newline. - /// - /// If not inside of a buffer the caret well be moved to the current language buffer if possible. - /// - /// Returns true if the return was successfully processed. - /// - bool Return(); - - /// - /// If the current input is a standard input this will submit the input. - /// - /// Returns true if the input was submitted, false otherwise. - /// - bool TrySubmitStandardInput(); - - /// - /// Resets the execution context clearing all variables. - /// - Task ResetAsync(bool initialize = true); - - /// - /// Executes the current input regardless of the caret position within the input. - /// - /// If the caret is in a previously executed input then the input is pasted to the - /// end of the current input and not executed. - /// - void ExecuteInput(); - - /// - /// Clears the current input. - /// - void Cancel(); - } -} diff --git a/src/InteractiveWindow/Editor/IInteractiveWindowOperations2.cs b/src/InteractiveWindow/Editor/IInteractiveWindowOperations2.cs deleted file mode 100644 index 5410c28d04a33..0000000000000 --- a/src/InteractiveWindow/Editor/IInteractiveWindowOperations2.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - public interface IInteractiveWindowOperations2 : IInteractiveWindowOperations - { - /// - /// Copies the current selection to the clipboard. - /// - void Copy(); - - /// - /// Copies code from user inputs to clipboard. - /// If selection is empty, then copy from current line, otherwise copy from selected lines. - /// - void CopyCode(); - - /// - /// Delete Line; Delete all selected lines, or the current line if no selection. - /// - void DeleteLine(); - - /// - /// Line Cut; Cut all selected lines, or the current line if no selection, to the clipboard. - /// - void CutLine(); - - /// - /// Handles character typed in by user. - /// - void TypeChar(char typedChar); - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveClipboardFormat.cs b/src/InteractiveWindow/Editor/InteractiveClipboardFormat.cs deleted file mode 100644 index 11d1232f16240..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveClipboardFormat.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// Implements deserialization for clipboard objects created by Interactive Window Copy operations. - /// - public static class InteractiveClipboardFormat - { - /// - /// Unique identifier for the clipboard format. - /// - public const string Tag = "89344A36-9821-495A-8255-99A63969F87D"; - - /// - /// Deserializes clipboard object. - /// - /// Object retrieved fromt the clipboard - /// The value is not of the expected format. - public static string Deserialize(object value) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - var text = value as string; - if (text == null) - { - throw new InvalidDataException(); - } - - var blocks = BufferBlock.Deserialize(text); - - var result = new StringBuilder(); - foreach (var block in blocks) - { - switch (block.Kind) - { - // the actual linebreak was converted to regular Input when copied - // This LineBreak block was created by coping box selection and is used as line separator when pasted - case ReplSpanKind.LineBreak: - result.Append(block.Content); - break; - - case ReplSpanKind.Input: - case ReplSpanKind.Output: - case ReplSpanKind.StandardInput: - result.Append(block.Content); - break; - } - } - - return result.ToString(); - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveContentTypeDefinitions.cs b/src/InteractiveWindow/Editor/InteractiveContentTypeDefinitions.cs deleted file mode 100644 index 6396b57ca3a5a..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveContentTypeDefinitions.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Utilities; - -#pragma warning disable CS0649 // field is not assigned to - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal static class InteractiveContentTypeDefinitions - { - [Export, Name(PredefinedInteractiveContentTypes.InteractiveContentTypeName), BaseDefinition("text"), BaseDefinition("projection")] - internal static readonly ContentTypeDefinition InteractiveContentTypeDefinition; - - [Export, Name(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName), BaseDefinition("text")] - internal static readonly ContentTypeDefinition InteractiveOutputContentTypeDefinition; - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.EditResolver.cs b/src/InteractiveWindow/Editor/InteractiveWindow.EditResolver.cs deleted file mode 100644 index c263c4e867969..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.EditResolver.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Projection; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal partial class InteractiveWindow - { - private sealed class EditResolver : IProjectionEditResolver - { - private readonly InteractiveWindow _window; - - public EditResolver(InteractiveWindow window) - { - _window = window; - } - - // We always favor the last buffer of our language type. This handles cases where we're on a boundary between a prompt and a language - // buffer - we favor the language buffer because the prompts cannot be edited. In the case of two language buffers this also works because - // our spans are laid out like: - // - // - // - // In the case where the prompts are in the margin we have an insertion conflict between the two language spans. But because - // lang span 1 includes the new line in order to be on the boundary we need to be on lang span 2's line. - // - // This works the same way w/ our input buffer where the input buffer present instead of . - - void IProjectionEditResolver.FillInInsertionSizes(SnapshotPoint projectionInsertionPoint, ReadOnlyCollection sourceInsertionPoints, string insertionText, IList insertionSizes) - { - int index = _window.UIThread(uiOnly => IndexOfEditableBuffer(sourceInsertionPoints, uiOnly)); - if (index != -1) - { - insertionSizes[index] = insertionText.Length; - } - } - - int IProjectionEditResolver.GetTypicalInsertionPosition(SnapshotPoint projectionInsertionPoint, ReadOnlyCollection sourceInsertionPoints) - { - int index = _window.UIThread(uiOnly => IndexOfEditableBuffer(sourceInsertionPoints, uiOnly)); - return index != -1 ? index : 0; - } - - void IProjectionEditResolver.FillInReplacementSizes(SnapshotSpan projectionReplacementSpan, ReadOnlyCollection sourceReplacementSpans, string insertionText, IList insertionSizes) - { - int index = _window.UIThread(uiOnly => IndexOfEditableBuffer(sourceReplacementSpans, uiOnly)); - if (index != -1) - { - insertionSizes[index] = insertionText.Length; - } - } - - private int IndexOfEditableBuffer(ReadOnlyCollection points, UIThreadOnly uiOnly) - { - Debug.Assert(_window.OnUIThread()); - for (int i = points.Count - 1; i >= 0; i--) - { - if (IsEditableBuffer(points[i].Snapshot.TextBuffer, uiOnly)) - { - return i; - } - } - - return -1; - } - - private int IndexOfEditableBuffer(ReadOnlyCollection spans, UIThreadOnly uiOnly) - { - Debug.Assert(_window.OnUIThread()); - for (int i = spans.Count - 1; i >= 0; i--) - { - if (IsEditableBuffer(spans[i].Snapshot.TextBuffer, uiOnly)) - { - return i; - } - } - - return -1; - } - - private bool IsEditableBuffer(ITextBuffer buffer, UIThreadOnly uiOnly) - { - return buffer == uiOnly.CurrentLanguageBuffer || buffer == uiOnly.StandardInputBuffer; - } - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.PendingSubmission.cs b/src/InteractiveWindow/Editor/InteractiveWindow.PendingSubmission.cs deleted file mode 100644 index 6b232729f0161..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.PendingSubmission.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal partial class InteractiveWindow - { - private class PendingSubmission - { - public readonly string Input; - - /// - /// Set only on the last submission in each batch (to notify the caller). - /// - public readonly TaskCompletionSource Completion; - - public Task Task; - - public PendingSubmission(string input, TaskCompletionSource completion) - { - Input = input; - Completion = completion; - } - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.ReplSpanKind.cs b/src/InteractiveWindow/Editor/InteractiveWindow.ReplSpanKind.cs deleted file mode 100644 index d9244c56c4587..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.ReplSpanKind.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Runtime.Serialization; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - [DataContract] - internal enum ReplSpanKind - { - /// - /// Primary, secondary, or standard input prompt. - /// - [EnumMember] - Prompt = 0, - - /// - /// The span represents output from the program (standard output). - /// - [EnumMember] - Output = 1, - - /// - /// The span represents code inputted after a prompt or secondary prompt. - /// - [EnumMember] - Input = 2, - - /// - /// The span represents the input for a standard input (non code input). - /// - [EnumMember] - StandardInput = 3, - - /// - /// Line break inserted at end of output. - /// - [EnumMember] - LineBreak = 4, - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.SpanRangeEdit.cs b/src/InteractiveWindow/Editor/InteractiveWindow.SpanRangeEdit.cs deleted file mode 100644 index fcd066c2fb1a4..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.SpanRangeEdit.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal partial class InteractiveWindow - { - private struct SpanRangeEdit - { - public readonly int Start; - public readonly int End; - public readonly object[] Replacement; - - public SpanRangeEdit(int start, int count, object[] replacement) - { - Start = start; - End = start + count; - Replacement = replacement; - } - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.State.cs b/src/InteractiveWindow/Editor/InteractiveWindow.State.cs deleted file mode 100644 index daac00a40e8e6..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.State.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal partial class InteractiveWindow - { - internal enum State - { - /// - /// Initial state. hasn't been called. - /// Transition to when is called. - /// Transition to when is called. - /// - Starting, - /// - /// In the process of calling . - /// Transition to when finished (in ). - /// Transition to when is called. - /// - Initializing, - /// - /// In the process of calling . - /// Transition to when finished (in ). - /// Transition to when is called - /// - Resetting, - /// - /// Prompt has been displayed - waiting for the user to make the next submission. - /// Transition to when is called. - /// Transition to when is called. - /// Transition to when is called - /// - WaitingForInput, - /// - /// Executing the user's submission. - /// Transition to when finished (in ). - /// Transition to when is called. - /// Transition to when is called - /// - ExecutingInput, - /// - /// In the process of calling (within ). - /// Transition to when , - /// , or - /// is called. - /// - ResettingAndReadingStandardInput, - /// - /// In the process of calling (while prompt has been displayed). - /// Transition to when or is called. - /// Transition to when is called. - /// - WaitingForInputAndReadingStandardInput, - /// - /// In the process of calling (while executing the user's submission). - /// Transition to when or is called. - /// Transition to when is called. - /// - ExecutingInputAndReadingStandardInput, - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.SystemClipboard.cs b/src/InteractiveWindow/Editor/InteractiveWindow.SystemClipboard.cs deleted file mode 100644 index 4320610447892..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.SystemClipboard.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Windows; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal partial class InteractiveWindow - { - private sealed class SystemClipboard : InteractiveWindowClipboard - { - internal override bool ContainsData(string format) => Clipboard.ContainsData(format); - - internal override object GetData(string format) => Clipboard.GetData(format); - - internal override bool ContainsText() => Clipboard.ContainsText(); - - internal override string GetText() => Clipboard.GetText(); - - internal override void SetDataObject(object data, bool copy) => Clipboard.SetDataObject(data, copy); - - internal override IDataObject GetDataObject() => Clipboard.GetDataObject(); - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.UIThreadOnly.cs b/src/InteractiveWindow/Editor/InteractiveWindow.UIThreadOnly.cs deleted file mode 100644 index c4f30a9cd180f..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.UIThreadOnly.cs +++ /dev/null @@ -1,3496 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; -using System.Windows.Threading; -using Microsoft.VisualStudio.Language.Intellisense; -using Microsoft.VisualStudio.Language.Intellisense.Utilities; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; -using Microsoft.VisualStudio.Text.Formatting; -using Microsoft.VisualStudio.Text.Operations; -using Microsoft.VisualStudio.Text.Projection; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal partial class InteractiveWindow - { - private sealed partial class UIThreadOnly : IDisposable - { - private const int SpansPerLineOfInput = 2; - - private static readonly object s_suppressPromptInjectionTag = new object(); - - private readonly InteractiveWindow _window; - - private readonly IInteractiveWindowEditorFactoryService _factory; - - private readonly ITextBufferFactoryService _textBufferFactoryService; - - private readonly ITextBufferUndoManagerProvider _textBufferUndoManagerProvider; - private ITextBufferUndoManager _undoManager; - - /// - /// Returns `null` to indicate we don't record undo history for operations in standard-input buffer. - /// This is exposed only for test purpose. - /// - public ITextUndoHistory UndoHistory => - ReadingStandardInput ? null : _undoManager.TextBufferUndoHistory; - - private readonly History _history = new History(); - private string _historySearch; - - private readonly ISmartIndentationService _smartIndenterService; - - // Pending submissions to be processed whenever the REPL is ready to accept submissions. - private readonly Queue _pendingSubmissions = new Queue(); - - private DispatcherTimer _executionTimer; - private Cursor _oldCursor; - private int _currentOutputProjectionSpan; - private int _outputTrackingCaretPosition = -1; - - private readonly IRtfBuilderService2 _rtfBuilderService; - - // Read-only regions protecting initial span of the corresponding buffers: - private readonly IReadOnlyRegion[] _standardInputProtection = new IReadOnlyRegion[2]; - private readonly IReadOnlyRegion[] _outputProtection = new IReadOnlyRegion[2]; - - private string _uncommittedInput; - - /// Always access through and . - private SnapshotSpan? _standardInputValue; - /// Don't reference directly. - private readonly SemaphoreSlim _standardInputValueGuard = new SemaphoreSlim(initialCount: 0, maxCount: 1); - - // State captured when we started reading standard input. - private int _standardInputStart = -1; - - /// Always access through . - private IIntellisenseSessionStack _sessionStack; // TODO: remove - private readonly IIntellisenseSessionStackMapService _intellisenseSessionStackMap; - - private bool _adornmentToMinimize; - - private readonly string _lineBreakString; - - private readonly IProjectionBuffer _projectionBuffer; - private readonly IContentType _inertType; - - private readonly OutputBuffer _buffer; - - private readonly IWaitIndicator _waitIndicator; - - public ITextBuffer OutputBuffer { get; } - public ITextBuffer StandardInputBuffer { get; } - public ITextBuffer CurrentLanguageBuffer { get; private set; } - - public readonly TextWriter OutputWriter; - public readonly InteractiveWindowWriter ErrorOutputWriter; - - // the language engine and content type of the active submission: - public readonly IInteractiveEvaluator Evaluator; - - public readonly IWpfTextView TextView; - - /// Always access through . - private IEditorOperations _editorOperations; - public IEditorOperations EditorOperations - { - get - { - return _editorOperations; - } - set - { - Debug.Assert(_editorOperations == null, "Assignment only happens once."); - Debug.Assert(value != null); - _editorOperations = value; - } - } - - /// Always access through . - private State _state; - - public State State - { - get - { - return _state; - } - set - { - _window.StateChanged?.Invoke(value); - _state = value; - } - } - - public UIThreadOnly( - InteractiveWindow window, - IInteractiveWindowEditorFactoryService factory, - IContentTypeRegistryService contentTypeRegistry, - ITextBufferFactoryService bufferFactory, - IProjectionBufferFactoryService projectionBufferFactory, - IEditorOperationsFactoryService editorOperationsFactory, - ITextBufferUndoManagerProvider textBufferUndoManagerProvider, - ITextEditorFactoryService editorFactory, - IRtfBuilderService rtfBuilderService, - IIntellisenseSessionStackMapService intellisenseSessionStackMap, - ISmartIndentationService smartIndenterService, - IInteractiveEvaluator evaluator, - IWaitIndicator waitIndicator) - { - _window = window; - _factory = factory; - _textBufferFactoryService = bufferFactory; - _textBufferUndoManagerProvider = textBufferUndoManagerProvider; - _rtfBuilderService = (IRtfBuilderService2)rtfBuilderService; - _intellisenseSessionStackMap = intellisenseSessionStackMap; - _smartIndenterService = smartIndenterService; - _waitIndicator = waitIndicator; - Evaluator = evaluator; - - var replContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName); - var replOutputContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName); - - OutputBuffer = bufferFactory.CreateTextBuffer(replOutputContentType); - StandardInputBuffer = bufferFactory.CreateTextBuffer(); - _standardInputStart = 0; - _inertType = bufferFactory.InertContentType; - - _projectionBuffer = projectionBufferFactory.CreateProjectionBuffer( - new EditResolver(window), - Array.Empty(), - ProjectionBufferOptions.None, - replContentType); - - _projectionBuffer.Properties.AddProperty(typeof(InteractiveWindow), window); - - AppendNewOutputProjectionBuffer(); - _projectionBuffer.Changed += new EventHandler(ProjectionBufferChanged); - - var roleSet = editorFactory.CreateTextViewRoleSet( - PredefinedTextViewRoles.Analyzable, - PredefinedTextViewRoles.Editable, - PredefinedTextViewRoles.Interactive, - PredefinedTextViewRoles.Zoomable, - PredefinedInteractiveTextViewRoles.InteractiveTextViewRole); - - TextView = factory.CreateTextView(window, _projectionBuffer, roleSet); - TextView.Caret.PositionChanged += CaretPositionChanged; - - var options = TextView.Options; - options.SetOptionValue(DefaultTextViewHostOptions.HorizontalScrollBarId, true); - options.SetOptionValue(DefaultTextViewHostOptions.LineNumberMarginId, false); - options.SetOptionValue(DefaultTextViewHostOptions.OutliningMarginId, false); - options.SetOptionValue(DefaultTextViewHostOptions.GlyphMarginId, false); - options.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.None); - - _lineBreakString = options.GetNewLineCharacter(); - EditorOperations = editorOperationsFactory.GetEditorOperations(TextView); - - _buffer = new OutputBuffer(window); - OutputWriter = new InteractiveWindowWriter(window, spans: null); - - SortedSpans errorSpans = new SortedSpans(); - ErrorOutputWriter = new InteractiveWindowWriter(window, errorSpans); - OutputClassifierProvider.AttachToBuffer(OutputBuffer, errorSpans); - } - - private bool ReadingStandardInput => - State == State.ExecutingInputAndReadingStandardInput || - State == State.WaitingForInputAndReadingStandardInput || - State == State.ResettingAndReadingStandardInput; - - /// Implements . - public async Task ResetAsync(bool initialize) - { - try - { - if (ReadingStandardInput) - { - MakeStandardInputReadonly(); - CancelStandardInput(); - } - - _buffer.Flush(); - - // Nothing to clear in WaitingForInputAndReadingStandardInput, since we cleared - // the language prompt when we entered that state. - if (State == State.WaitingForInput) - { - var snapshot = _projectionBuffer.CurrentSnapshot; - var spanCount = snapshot.SpanCount; - Debug.Assert(GetSpanKind(snapshot.GetSourceSpan(spanCount - 1)) == ReplSpanKind.Input); - StoreUncommittedInput(); - RemoveProjectionSpans(spanCount - 2, 2); - CurrentLanguageBuffer = null; - } - - State = State.Resetting; - var executionResult = await Evaluator.ResetAsync(initialize).ConfigureAwait(true); - Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. - - Debug.Assert(State == State.Resetting, $"Unexpected state {State}"); - FinishExecute(executionResult.IsSuccessful); - - return executionResult; - } - catch (Exception e) when (_window.ReportAndPropagateException(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - /// Implements . - public void Close() - { - TextView.Caret.PositionChanged -= CaretPositionChanged; - TextView.Close(); - } - - /// Implements . - public void ClearHistory() - { - _history.Clear(); - } - - /// Implements . - public void ClearView() - { - if (ReadingStandardInput) - { - CancelStandardInput(); - State = GetStateBeforeReadingStandardInput(State); - Debug.Assert(State == State.ExecutingInput || State == State.WaitingForInput); - } - - _adornmentToMinimize = false; - InlineAdornmentProvider.RemoveAllAdornments(TextView); - - // remove all the spans except our initial span from the projection buffer - _uncommittedInput = null; - - // We remove all spans from the projection buffer *before* updating the - // subject buffers so that composite/merged changes to the projection - // buffer don't have to be computed. This seems to alleviate the problem - // we were having with OutOfMemoryExceptions when clearing large output - // buffers (which did not, themselves, trigger OOMs). - RemoveProjectionSpans(0, _projectionBuffer.CurrentSnapshot.SpanCount); - - // Clear the projection and buffers last as this might trigger events that might access other state of the REPL window: - RemoveProtection(OutputBuffer, _outputProtection); - RemoveProtection(StandardInputBuffer, _standardInputProtection); - - using (var edit = OutputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag)) - { - edit.Delete(0, OutputBuffer.CurrentSnapshot.Length); - edit.Apply(); - } - - _buffer.Reset(); - OutputClassifierProvider.ClearSpans(OutputBuffer); - _outputTrackingCaretPosition = 0; - - using (var edit = StandardInputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag)) - { - edit.Delete(0, StandardInputBuffer.CurrentSnapshot.Length); - edit.Apply(); - } - - // Insert an empty output buffer. - // We do it for two reasons: - // 1) When output is written to asynchronously we need a buffer to store it. - // This may happen when clearing screen while background thread is writing to the console. - // 2) We need at least one non-inert span due to bugs in projection buffer. - AppendNewOutputProjectionBuffer(); - - _history.ForgetOriginalBuffers(); - - // If we were waiting for input, we need to restore the prompt that we just cleared. - // If we are in any other state, then we'll let normal transitions trigger the next prompt. - if (State == State.WaitingForInput) - { - PrepareForInput(); - } - } - - private static State GetStateBeforeReadingStandardInput(State state) - { - switch (state) - { - case State.WaitingForInputAndReadingStandardInput: - return State.WaitingForInput; - case State.ExecutingInputAndReadingStandardInput: - return State.ExecutingInput; - case State.ResettingAndReadingStandardInput: - return State.Resetting; - default: - throw ExceptionUtilities.UnexpectedValue(state); - } - } - - /// Implements the core of . - public async Task ReadStandardInputAsync() - { - try - { - switch (State) - { - case State.Starting: - case State.Initializing: - throw new InvalidOperationException(InteractiveWindowResources.NotInitialized); - - case State.WaitingForInputAndReadingStandardInput: - case State.ExecutingInputAndReadingStandardInput: - case State.ResettingAndReadingStandardInput: - // Guarded by semaphore. - throw ExceptionUtilities.UnexpectedValue(State); - - case State.WaitingForInput: - State = State.WaitingForInputAndReadingStandardInput; - break; - case State.ExecutingInput: - State = State.ExecutingInputAndReadingStandardInput; - break; - case State.Resetting: - State = State.ResettingAndReadingStandardInput; - break; - - default: - throw ExceptionUtilities.UnexpectedValue(State); - } - - Debug.Assert(ReadingStandardInput); - - // disable undo for current language buffer so undo/redo is greyed out when reading standard input - if (CurrentLanguageBuffer != null && CurrentLanguageBuffer.IsReadOnly(0)) - { - _undoManager.UnregisterUndoHistory(); - _textBufferUndoManagerProvider.RemoveTextBufferUndoManager(CurrentLanguageBuffer); - } - - _buffer.Flush(); - - if (State == State.WaitingForInputAndReadingStandardInput) - { - var snapshot = _projectionBuffer.CurrentSnapshot; - var spanCount = snapshot.SpanCount; - if (spanCount > 0 && GetSpanKind(snapshot.GetSourceSpan(spanCount - 1)) == ReplSpanKind.Input) - { - // we need to remove our input prompt. - RemoveLastInputPrompt(); - } - } - - AddStandardInputSpan(); - - TextView.Caret.EnsureVisible(); - ResetCursor(); - - _uncommittedInput = null; - - var value = await GetStandardInputValue().ConfigureAwait(true); - Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. - - // set new start location after read is done. - _standardInputStart = StandardInputBuffer.CurrentSnapshot.Length; - - return value.HasValue - ? new StringReader(value.GetValueOrDefault().GetText()) - : null; - } - catch (Exception e) when (_window.ReportAndPropagateException(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - private void CancelStandardInput() - { - SetStandardInputValue(null); - } - - private void SetStandardInputValue(SnapshotSpan? value) - { - _standardInputValue = value; - _standardInputValueGuard.Release(); - } - - private async Task GetStandardInputValue() - { - try - { - await _standardInputValueGuard.WaitAsync().ConfigureAwait(true); - Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. - return _standardInputValue; - } - catch (Exception e) when (_window.ReportAndPropagateException(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - private Span GetStandardInputSpan() - { - return Span.FromBounds(_standardInputStart, StandardInputBuffer.CurrentSnapshot.Length); - } - - private void MakeStandardInputReadonly() - { - AppendLineNoPromptInjection(StandardInputBuffer); - - // We can also have an interleaving output span, so we'll search back for the last input span. - var sourceSpans = _projectionBuffer.CurrentSnapshot.GetSourceSpans(); - - int index = IndexOfLastSpan(sourceSpans, ReplSpanKind.StandardInput); - Debug.Assert(index >= 0); - - RemoveProtection(StandardInputBuffer, _standardInputProtection); - - // replace previous span w/ a span that won't grow... - var oldSpan = sourceSpans[index]; - var newSpan = new CustomTrackingSpan(oldSpan.Snapshot, oldSpan.Span); - - ReplaceProjectionSpan(index, newSpan); - ApplyProtection(StandardInputBuffer, _standardInputProtection, allowAppend: true); - } - - private void AppendLineNoPromptInjection(ITextBuffer buffer) - { - using (var edit = buffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag)) - { - edit.Insert(buffer.CurrentSnapshot.Length, _lineBreakString); - edit.Apply(); - } - } - - /// Implements . - public void TypeChar(char typedChar) - { - using (var transaction = UndoHistory?.CreateTransaction(InteractiveWindowResources.TypeChar)) - { - if (transaction != null) - { - var mergeDirections = TextTransactionMergeDirections.Forward | TextTransactionMergeDirections.Backward; - // replacing selected text should be an atomic undo operation). - if ((!TextView.Selection.IsEmpty && !IsEmptyBoxSelection())) - { - mergeDirections = TextTransactionMergeDirections.Forward; - } - transaction.MergePolicy = new TextTransactionMergePolicy(mergeDirections); - } - - if (InsertText(typedChar.ToString())) - { - transaction?.Complete(); - } - } - } - - /// Implements . - public void InsertCode(string text) - { - if (ReadingStandardInput) - { - return; - } - - if (State == State.ExecutingInput) - { - AppendUncommittedInput(text); - } - else - { - InsertText(text); - } - } - - private bool InsertText(string text) - { - var selection = TextView.Selection; - var caretPosition = TextView.Caret.Position.BufferPosition; - if (!TextView.Selection.IsEmpty) - { - if (!IsSelectionInsideCurrentSubmission()) - { - return false; - } - - DeleteSelection(); - - if (selection.Mode == TextSelectionMode.Box) - { - ReduceBoxSelectionToEditableBox(isDelete: true); - } - else - { - selection.Clear(); - MoveCaretToClosestEditableBuffer(); - } - } - else if (IsInActivePrompt(caretPosition)) - { - MoveCaretToClosestEditableBuffer(); - } - else if (MapToEditableBuffer(caretPosition) == null) - { - return false; - } - - return EditorOperations.InsertText(text); - } - - /// Implements the core of . - public void Submit(PendingSubmission[] pendingSubmissions) - { - if (!ReadingStandardInput) - { - if (State == State.WaitingForInput && CurrentLanguageBuffer != null) - { - StoreUncommittedInput(); - PendSubmissions(pendingSubmissions); - ProcessPendingSubmissions(); - } - else - { - PendSubmissions(pendingSubmissions); - } - } - } - - private void StoreUncommittedInput() - { - if (_uncommittedInput == null) - { - string activeCode = GetActiveCode(); - if (!string.IsNullOrEmpty(activeCode)) - { - _uncommittedInput = activeCode; - } - } - } - - /// - /// Returns the full text of the current active input. - /// - private string GetActiveCode() - { - return CurrentLanguageBuffer.CurrentSnapshot.GetText(); - } - - private void PendSubmissions(IEnumerable inputs) - { - foreach (var input in inputs) - { - _pendingSubmissions.Enqueue(input); - } - } - - /// Implements . - public void FlushOutput() - { - _buffer.Flush(); - } - - /// Implements . - public void AddInput(string command) - { - // If the language buffer is readonly then input can not be added. Return immediately. - // The language buffer gets marked as readonly in SubmitAsync method when input on the prompt - // gets submitted. So it would be readonly when the user types #reset on the prompt. In that - // case it is the right thing to bail out of this method. - if (CurrentLanguageBuffer != null && CurrentLanguageBuffer.IsReadOnly(0)) - { - return; - } - - if (State == State.ExecutingInput || CurrentLanguageBuffer == null) - { - AddLanguageBuffer(); - CurrentLanguageBuffer.Insert(0, command); - } - else - { - StoreUncommittedInput(); - SetActiveCode(command); - } - - // Add command to history before calling FinishCurrentSubmissionInput as it adds newline - // to the end of the command. - _history.Add(CurrentLanguageBuffer.CurrentSnapshot.GetExtent()); - FinishCurrentSubmissionInput(); - } - - /// Implements . - public void AddToHistory(string command) - { - if (string.IsNullOrEmpty(command)) - { - return; - } - - _buffer.Flush(); - - var sourceSpans = _projectionBuffer.CurrentSnapshot.GetSourceSpans(); - int insertionIndex; - switch (State) - { - case State.Starting: - case State.Initializing: - throw new InvalidOperationException(InteractiveWindowResources.NotInitialized); - case State.Resetting: - case State.ResettingAndReadingStandardInput: - throw new InvalidOperationException(InteractiveWindowResources.IsResettings); - case State.ExecutingInput: - insertionIndex = sourceSpans.Count; - break; - case State.ExecutingInputAndReadingStandardInput: - case State.WaitingForInput: - case State.WaitingForInputAndReadingStandardInput: - insertionIndex = IndexOfLastSpan(sourceSpans, ReplSpanKind.Prompt); - if (insertionIndex == -1) - { - insertionIndex = 0; - } - - break; - default: - throw ExceptionUtilities.UnexpectedValue(State); - } - - IContentType contentType; - if (!((IPropertyOwner)_window).Properties.TryGetProperty(typeof(IContentType), out contentType)) - { - contentType = _textBufferFactoryService.TextContentType; - } - - var historyBuffer = _textBufferFactoryService.CreateTextBuffer(contentType); - historyBuffer.Properties.AddProperty(typeof(IInteractiveEvaluator), Evaluator); - historyBuffer.Properties.AddProperty(typeof(InteractiveWindow), _window); - - using (var edit = historyBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag)) - { - if (!command.EndsWith(_lineBreakString)) - { - edit.Insert(0, command + _lineBreakString); - } - else - { - edit.Insert(0, command); - } - edit.Apply(); - } - var end = historyBuffer.CurrentSnapshot.Length; - - var historySpan = new SnapshotSpan(historyBuffer.CurrentSnapshot, Span.FromBounds(0, end -_lineBreakString.Length)); - _history.Add(historySpan); - - // If current output buffer span is empty, it is safe to add history span before it instead of creating a new output buffer span - if (_currentOutputProjectionSpan + 1 == insertionIndex && sourceSpans[_currentOutputProjectionSpan].IsEmpty) - { - insertionIndex--; - } - else - { - NewOutputBuffer(insertionIndex); - } - - var trackingSpan = new CustomTrackingSpan(historyBuffer.CurrentSnapshot, Span.FromBounds(0, end)); - InsertProjectionSpans(insertionIndex, CreatePrimaryPrompt(), trackingSpan); - } - - private void AppendUncommittedInput(string text) - { - if (string.IsNullOrEmpty(text)) - { - // Do nothing. - } - else if (string.IsNullOrEmpty(_uncommittedInput)) - { - _uncommittedInput = text; - } - else - { - _uncommittedInput += text; - } - } - - private void RestoreUncommittedInput() - { - if (_uncommittedInput != null) - { - SetActiveCode(_uncommittedInput); - _uncommittedInput = null; - } - } - - private bool IsCaretOnBlankEditableLine() - { - var position = MapToEditableBuffer(TextView.Caret.Position.BufferPosition.GetContainingLine().EndIncludingLineBreak); - // readonly line - if (!position.HasValue) - { - return false; - } - // non-blank line - else if (IndexOfNonWhiteSpaceCharacter(position.GetValueOrDefault().GetContainingLine()) >= 0) - { - return false; - } - else - { - return true; - } - } - - private void MoveCaretToClosestEditableBuffer() - { - SnapshotPoint currentPosition = TextView.Caret.Position.BufferPosition; - SnapshotPoint newPosition = GetClosestEditablePoint(currentPosition); - if (currentPosition != newPosition) - { - TextView.Caret.MoveTo(newPosition); - } - } - - /// - /// Finds a point in an editable buffer that is the closest towards the end to the given projection point. - /// - private SnapshotPoint GetClosestEditablePoint(SnapshotPoint projectionPoint) - { - ITextBuffer editableBuffer = ReadingStandardInput ? StandardInputBuffer : CurrentLanguageBuffer; - - if (editableBuffer == null) - { - return new SnapshotPoint(_projectionBuffer.CurrentSnapshot, _projectionBuffer.CurrentSnapshot.Length); - } - - SnapshotPoint? point = GetPositionInBuffer(projectionPoint, editableBuffer); - if (point != null) - { - return projectionPoint; - } - - var projectionLine = projectionPoint.GetContainingLine(); - - SnapshotPoint? lineEnd = TextView.BufferGraph.MapDownToBuffer( - projectionLine.End, - PointTrackingMode.Positive, - editableBuffer, - PositionAffinity.Successor); - - SnapshotPoint editablePoint; - if (lineEnd == null) - { - editablePoint = new SnapshotPoint(editableBuffer.CurrentSnapshot, 0); - } - else - { - editablePoint = lineEnd.Value.GetContainingLine().Start; - } - - return TextView.BufferGraph.MapUpToBuffer( - editablePoint, - PointTrackingMode.Positive, - PositionAffinity.Successor, - _projectionBuffer).Value; - } - - /// - /// Appends given text to the last input span (standard input or active code input). - /// - private void AppendInput(string text) - { - var snapshot = _projectionBuffer.CurrentSnapshot; - var spanCount = snapshot.SpanCount; - var inputSpan = snapshot.GetSourceSpan(spanCount - 1); - Debug.Assert(GetSpanKind(inputSpan) == ReplSpanKind.Input || - GetSpanKind(inputSpan) == ReplSpanKind.StandardInput); - - var buffer = inputSpan.Snapshot.TextBuffer; - var span = inputSpan.Span; - using (var edit = buffer.CreateEdit()) - { - edit.Insert(edit.Snapshot.Length, text); - edit.Apply(); - } - - var replSpan = new CustomTrackingSpan( - buffer.CurrentSnapshot, - new Span(span.Start, span.Length + text.Length), - canAppend: true); - ReplaceProjectionSpan(spanCount - 1, replSpan); - - TextView.Caret.EnsureVisible(); - } - - public void PrepareForInput() - { - _buffer.Flush(); - AddLanguageBuffer(); - State = State.WaitingForInput; - - // we are prepared for processing any postponed submissions there might have been: - ProcessPendingSubmissions(); - } - - private void ProcessPendingSubmissions() - { - Debug.Assert(CurrentLanguageBuffer != null); - - if (_pendingSubmissions.Count == 0) - { - RestoreUncommittedInput(); - - // move to the end (it might have been in virtual space): - TextView.Caret.MoveTo(GetLastLine(TextView.TextBuffer.CurrentSnapshot).End); - TextView.Caret.EnsureVisible(); - _window.ReadyForInput?.Invoke(); - - return; - } - - var submission = _pendingSubmissions.Dequeue(); - SetActiveCode(submission.Input); - Debug.Assert(submission.Task == null, "Someone set PendingSubmission.Task before it was dequeued."); - submission.Task = SubmitAsync(); - if (submission.Completion != null) - { - // ContinueWith is safe since TaskCompletionSource.SetResult should not throw. - // Therefore, we don't need to await the task (which we would normally do to - // propagate any exceptions it might throw). We also don't need an NFW - // exception filter around the continuation. - submission.Task.ContinueWith(_ => submission.Completion.SetResult(null), TaskScheduler.Current); - } - } - - #region Editor Helpers - - private static ITextSnapshotLine GetLastLine(ITextSnapshot snapshot) - { - return snapshot.GetLineFromLineNumber(snapshot.LineCount - 1); - } - - private static int IndexOfNonWhiteSpaceCharacter(ITextSnapshotLine line) - { - var snapshot = line.Snapshot; - int start = line.Start.Position; - int count = line.Length; - for (int i = 0; i < count; i++) - { - if (!char.IsWhiteSpace(snapshot[start + i])) - { - return i; - } - } - - return -1; - } - - #endregion - - private async Task SubmitAsync() - { - try - { - RequiresLanguageBuffer(); - - // TODO: queue submission - // Ensure that the REPL doesn't try to execute if it is already - // executing. If this invariant can no longer be maintained more of - // the code in this method will need to be bullet-proofed - if (State == State.ExecutingInput) - { - return; - } - - // get command to save to history before calling FinishCurrentSubmissionInput - // as it adds newline at the end - var historySpan = CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); - FinishCurrentSubmissionInput(); - - _history.UncommittedInput = null; - - var snapshotSpan = CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); - var trimmedSpan = snapshotSpan.TrimEnd(); - if (trimmedSpan.Length > 0) - { - _history.Add(historySpan); - } - - State = State.ExecutingInput; - - StartCursorTimer(); - - var executionResult = await Evaluator.ExecuteCodeAsync(snapshotSpan.GetText()).ConfigureAwait(true); - Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. - - // For reset command typed at prompt -> the state should be WaitingForInput. - // For all other submissions on the prompt -> it should be Executing input. - // If reset button is clicked during a long running submission -> it could be Resetting because - // oldService is disposed first as part of resetting, which leads to await call above returning, and new service is - // created after that as part of completing the resetting process. - Debug.Assert(State == State.ExecutingInput || - State == State.WaitingForInput || - State == State.Resetting, $"Unexpected state {State}"); - - if (State == State.ExecutingInput) - { - FinishExecute(executionResult.IsSuccessful); - } - } - catch (Exception e) when (_window.ReportAndPropagateException(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - private void RequiresLanguageBuffer() - { - if (CurrentLanguageBuffer == null) - { - Environment.FailFast("Language buffer not available"); - } - } - - private void FinishCurrentSubmissionInput() - { - AppendLineNoPromptInjection(CurrentLanguageBuffer); - ApplyProtection(CurrentLanguageBuffer, regions: null); - - if (_adornmentToMinimize) - { - // TODO (tomat): remember the index of the adornment(s) in the current output and minimize those instead of the last one - InlineAdornmentProvider.MinimizeLastInlineAdornment(TextView); - _adornmentToMinimize = false; - } - - NewOutputBuffer(); - } - - /// - /// Marks the entire buffer as read-only. - /// - private void ApplyProtection(ITextBuffer buffer, IReadOnlyRegion[] regions, bool allowAppend = false) - { - using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit()) - { - int end = buffer.CurrentSnapshot.Length; - Span span = new Span(0, end); - - var region0 = allowAppend ? - readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow) : - readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny); - - // Create a second read-only region to prevent insert at start of buffer. - var region1 = (end > 0) ? readonlyEdit.CreateReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny) : null; - - readonlyEdit.Apply(); - - if (regions != null) - { - regions[0] = region0; - regions[1] = region1; - } - } - } - - /// - /// Removes read-only region from buffer. - /// - private void RemoveProtection(ITextBuffer buffer, IReadOnlyRegion[] regions) - { - if (regions[0] != null) - { - Debug.Assert(regions[1] != null); - - foreach (var region in regions) - { - using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit()) - { - readonlyEdit.RemoveReadOnlyRegion(region); - readonlyEdit.Apply(); - } - } - } - } - - private void NewOutputBuffer() - { - NewOutputBuffer(_projectionBuffer.CurrentSnapshot.SpanCount); - } - - private void NewOutputBuffer(int outputBufferPosition) - { - // Stop growing the current output projection span. - var sourceSpan = _projectionBuffer.CurrentSnapshot.GetSourceSpan(_currentOutputProjectionSpan); - Debug.Assert(GetSpanKind(sourceSpan) == ReplSpanKind.Output); - var nonGrowingSpan = new CustomTrackingSpan( - sourceSpan.Snapshot, - sourceSpan.Span); - ReplaceProjectionSpan(_currentOutputProjectionSpan, nonGrowingSpan); - - AppendNewOutputProjectionBuffer(outputBufferPosition); - _outputTrackingCaretPosition = TextView.Caret.Position.BufferPosition; - } - - private void AppendNewOutputProjectionBuffer() - { - AppendNewOutputProjectionBuffer(_projectionBuffer.CurrentSnapshot.SpanCount); - } - - private void AppendNewOutputProjectionBuffer(int outputBufferPosition) - { - var currentSnapshot = OutputBuffer.CurrentSnapshot; - var trackingSpan = new CustomTrackingSpan(currentSnapshot, new Span(currentSnapshot.Length, 0), canAppend: true); - - InsertProjectionSpans(outputBufferPosition, trackingSpan); - _currentOutputProjectionSpan = outputBufferPosition; - } - - private void InsertProjectionSpans(int index, params object[] spans) - { - _projectionBuffer.ReplaceSpans(index, 0, spans, EditOptions.None, editTag: s_suppressPromptInjectionTag); - if (index <= _currentOutputProjectionSpan) - { - _currentOutputProjectionSpan += spans.Length; - } - } - - private void ReplaceProjectionSpan(int spanToReplace, ITrackingSpan newSpan) - { - _projectionBuffer.ReplaceSpans(spanToReplace, 1, new[] { newSpan }, EditOptions.None, editTag: s_suppressPromptInjectionTag); - } - - private void RemoveProjectionSpans(int index, int count) - { - _projectionBuffer.ReplaceSpans(index, count, Array.Empty(), EditOptions.None, s_suppressPromptInjectionTag); - } - - /// - /// Appends text to the output buffer and updates projection buffer to include it. - /// WARNING: this has to be the only method that writes to the output buffer so that - /// the output buffering counters are kept in sync. - /// - internal void AppendOutput(IEnumerable output) - { - Debug.Assert(output.Any()); - - // we maintain this invariant so that projections don't split "\r\n" in half: - Debug.Assert(!OutputBuffer.CurrentSnapshot.EndsWith('\r')); - - var projectionSpans = _projectionBuffer.CurrentSnapshot.GetSourceSpans(); - Debug.Assert(GetSpanKind(projectionSpans[_currentOutputProjectionSpan]) == ReplSpanKind.Output); - - int lineBreakProjectionSpanIndex = _currentOutputProjectionSpan + 1; - - // insert line break projection span if there is none and the output doesn't end with a line break: - bool hasLineBreakProjection = false; - if (lineBreakProjectionSpanIndex < projectionSpans.Count) - { - var oldSpan = projectionSpans[lineBreakProjectionSpanIndex]; - hasLineBreakProjection = GetSpanKind(oldSpan) == ReplSpanKind.LineBreak; - } - - Debug.Assert(output.Last().Last() != '\r'); - bool endsWithLineBreak = output.Last().Last() == '\n'; - - // insert text to the subject buffer. - int oldBufferLength = OutputBuffer.CurrentSnapshot.Length; - InsertOutput(output, oldBufferLength); - - if (endsWithLineBreak && hasLineBreakProjection) - { - // Remove line break. - RemoveProjectionSpans(lineBreakProjectionSpanIndex, 1); - } - else if (!endsWithLineBreak && !hasLineBreakProjection) - { - // Insert line break. - InsertProjectionSpans(lineBreakProjectionSpanIndex, _lineBreakString); - } - - // caret didn't move since last time we moved it to track output: - if (_outputTrackingCaretPosition == TextView.Caret.Position.BufferPosition) - { - TextView.Caret.EnsureVisible(); - _outputTrackingCaretPosition = TextView.Caret.Position.BufferPosition; - } - } - - private void InsertOutput(IEnumerable output, int position) - { - RemoveProtection(OutputBuffer, _outputProtection); - - // append the text to output buffer and make sure it ends with a line break: - using (var edit = OutputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag)) - { - foreach (string text in output) - { - edit.Insert(position, text); - } - - edit.Apply(); - } - - ApplyProtection(OutputBuffer, _outputProtection); - } - - private void FinishExecute(bool succeeded) - { - ResetCursor(); - - if (!succeeded && _history.Last != null) - { - _history.Last.Failed = true; - } - - PrepareForInput(); - } - - /// Implements . - public async Task ExecuteInputAsync() - { - try - { - ITextBuffer languageBuffer = GetLanguageBuffer(TextView.Caret.Position.BufferPosition); - if (languageBuffer == null) - { - return; - } - - if (languageBuffer == CurrentLanguageBuffer) - { - // TODO (tomat): this should rather send an abstract "finish" command that various features - // can implement as needed (IntelliSense, inline rename would commit, etc.). - // For now, commit IntelliSense: - var completionSession = SessionStack.TopSession as ICompletionSession; - if (completionSession != null) - { - completionSession.Commit(); - } - - await SubmitAsync().ConfigureAwait(true); - Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. - } - else - { - // append text of the target buffer to the current language buffer: - string text = TrimTrailingEmptyLines(languageBuffer.CurrentSnapshot); - CurrentLanguageBuffer.Replace(new Span(CurrentLanguageBuffer.CurrentSnapshot.Length, 0), text); - EditorOperations.MoveToEndOfDocument(false); - } - } - catch (Exception e) when (_window.ReportAndPropagateException(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - private IIntellisenseSessionStack SessionStack - { - get - { - if (_sessionStack == null) - { - _sessionStack = _intellisenseSessionStackMap.GetStackForTextView(TextView); - } - - return _sessionStack; - } - } - - private static string TrimTrailingEmptyLines(ITextSnapshot snapshot) - { - var line = GetLastLine(snapshot); - while (line != null && line.Length == 0) - { - line = GetPreviousLine(line); - } - - if (line == null) - { - return string.Empty; - } - - return line.Snapshot.GetText(0, line.Extent.End.Position); - } - - private static ITextSnapshotLine GetPreviousLine(ITextSnapshotLine line) - { - return line.LineNumber > 0 ? line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1) : null; - } - - /// - /// Returns the language or command text buffer that the specified point belongs to. - /// If the point lays in a prompt returns the buffer corresponding to the prompt. - /// - /// The language or command buffer or null if the point doesn't belong to any. - private ITextBuffer GetLanguageBuffer(SnapshotPoint point) - { - var sourceSpans = GetSourceSpans(point.Snapshot); - int promptIndex = GetPromptIndexForPoint(sourceSpans, point); - if (promptIndex < 0) - { - return null; - } - - // Grab the span following the prompt (either language or standard input). - var projectionSpan = sourceSpans[promptIndex + 1]; - var kind = GetSpanKind(projectionSpan); - if (kind != ReplSpanKind.Input) - { - Debug.Assert(kind == ReplSpanKind.StandardInput); - return null; - } - - var inputSnapshot = projectionSpan.Snapshot; - var inputBuffer = inputSnapshot.TextBuffer; - - var projectedSpans = TextView.BufferGraph.MapUpToBuffer( - new SnapshotSpan(inputSnapshot, 0, inputSnapshot.Length), - SpanTrackingMode.EdgePositive, - _projectionBuffer); - - Debug.Assert(projectedSpans.Count > 0); - var projectedSpansStart = projectedSpans.First().Start; - var projectedSpansEnd = projectedSpans.Last().End; - - if (point < projectedSpansStart.GetContainingLine().Start) - { - return null; - } - - // If the buffer is the current buffer, the cursor might be in a virtual space behind the buffer - // but logically it belongs to the current submission. Since the current language buffer is the last buffer in the - // projection we don't need to check for its end. - if (inputBuffer == CurrentLanguageBuffer) - { - return inputBuffer; - } - - // if the point is at the end of the buffer it might be on the next line that doesn't logically belong to the input region: - if (point > projectedSpansEnd || (point == projectedSpansEnd && projectedSpansEnd.GetContainingLine().LineBreakLength != 0)) - { - return null; - } - - return inputBuffer; - } - - private int GetPromptIndexForPoint(ReadOnlyCollection sourceSpans, SnapshotPoint point) - { - int index = GetSourceSpanIndex(sourceSpans, point); - if (index == sourceSpans.Count) - { - index--; - } - // Find the nearest preceding prompt. - while (index >= 0 && !IsPrompt(sourceSpans[index])) - { - index--; - } - return index; - } - - private bool IsInActivePrompt(SnapshotPoint point) - { - var editableBuffer = ReadingStandardInput ? StandardInputBuffer : CurrentLanguageBuffer; - if (editableBuffer == null) - { - return false; - } - - var sourceSpans = GetSourceSpans(point.Snapshot); - var index = GetSourceSpanIndex(sourceSpans, point); - if (index == sourceSpans.Count) - { - index--; - } - - if (!IsPrompt(sourceSpans[index])) - { - return false; - } - - Debug.Assert(index + 1 < sourceSpans.Count); - var followingSpan = sourceSpans[index + 1]; - // if the following span is editable, then the prompt is active. - return GetPositionInBuffer(followingSpan.Start, editableBuffer) != null; - } - - /// - /// Return the index of the span containing the point. Returns the - /// length of the collection if the point is at the end of the last span. - /// - private int GetSourceSpanIndex(ReadOnlyCollection sourceSpans, SnapshotPoint point) - { - int low = 0; - int high = sourceSpans.Count; - while (low < high) - { - int mid = low + (high - low) / 2; - int value = CompareToSpan(TextView, sourceSpans, mid, point); - if (value == 0) - { - return mid; - } - else if (value < 0) - { - high = mid - 1; - } - else - { - low = mid + 1; - } - } - Debug.Assert(low >= 0); - Debug.Assert(low <= sourceSpans.Count); - return low; - } - - /// - /// Returns negative value if the point is less than the span start, - /// positive if greater than or equal to the span end, and 0 otherwise. - /// - private static int CompareToSpan(ITextView textView, ReadOnlyCollection sourceSpans, int index, SnapshotPoint point) - { - // If this span is zero-width and there are multiple projections of the - // containing snapshot in the projection buffer, MapUpToBuffer will return - // multiple (ambiguous) projection spans. To avoid that, we compare the - // point to the end point of the nearest non-zero width span instead. - int indexToCompare = index; - while (sourceSpans[indexToCompare].IsEmpty) - { - if (indexToCompare == 0) - { - // Empty span at start of buffer. Point - // must be to the right of span. - return 1; - } - indexToCompare--; - } - - var sourceSpan = sourceSpans[indexToCompare]; - Debug.Assert(sourceSpan.Length > 0); - - var mappedSpans = textView.BufferGraph.MapUpToBuffer(sourceSpan, SpanTrackingMode.EdgeInclusive, textView.TextBuffer); - Debug.Assert(mappedSpans.Count == 1); - - var mappedSpan = mappedSpans[0]; - Debug.Assert(mappedSpan.Length == sourceSpan.Length); - - if (indexToCompare < index) - { - var result = point.CompareTo(mappedSpan.End); - return (result == 0) ? 1 : result; - } - else - { - var result = point.CompareTo(mappedSpan.Start); - if (result <= 0) - { - return result; - } - result = point.CompareTo(mappedSpan.End); - return (result < 0) ? 0 : 1; - } - } - - private static ReadOnlyCollection GetSourceSpans(ITextSnapshot snapshot) - { - return ((IProjectionSnapshot)snapshot).GetSourceSpans(); - } - - private bool IsPrompt(SnapshotSpan span) - { - return GetSpanKind(span) == ReplSpanKind.Prompt; - } - - private void ResetCursor() - { - if (_executionTimer != null) - { - _executionTimer.Stop(); - } - - if (_oldCursor != null) - { - ((ContentControl)TextView).Cursor = _oldCursor; - } - - _oldCursor = null; - _executionTimer = null; - } - - private void StartCursorTimer() - { - var timer = new DispatcherTimer(); - timer.Tick += SetRunningCursor; - timer.Interval = TimeSpan.FromMilliseconds(250); - _executionTimer = timer; - timer.Start(); - } - - private void SetRunningCursor(object sender, EventArgs e) - { - var view = (ContentControl)TextView; - - // Save the old value of the cursor so it can be restored - // after execution has finished - _oldCursor = view.Cursor; - - // TODO: Design work to come up with the correct cursor to use - // Set the repl's cursor to the "executing" cursor - view.Cursor = Cursors.Wait; - - // Stop the timer so it doesn't fire again - if (_executionTimer != null) - { - _executionTimer.Stop(); - } - } - - private void RemoveLastInputPrompt() - { - var snapshot = _projectionBuffer.CurrentSnapshot; - var spanCount = snapshot.SpanCount; - Debug.Assert(IsPrompt(snapshot.GetSourceSpan(spanCount - SpansPerLineOfInput))); - - // projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping: - RemoveProjectionSpans(spanCount - SpansPerLineOfInput, SpansPerLineOfInput); - } - - /// - /// Creates and adds a new language buffer to the projection buffer. - /// - private void AddLanguageBuffer() - { - ITextBuffer buffer = _factory.CreateAndActivateBuffer(_window); - - if (CurrentLanguageBuffer != null) - { - _undoManager.UnregisterUndoHistory(); - _textBufferUndoManagerProvider.RemoveTextBufferUndoManager(CurrentLanguageBuffer); - } - _undoManager = _textBufferUndoManagerProvider.GetTextBufferUndoManager(buffer); - - buffer.Properties.AddProperty(typeof(IInteractiveEvaluator), Evaluator); - buffer.Properties.AddProperty(typeof(InteractiveWindow), _window); - - CurrentLanguageBuffer = buffer; - _window.SubmissionBufferAdded?.Invoke(_window, new SubmissionBufferAddedEventArgs(buffer)); - - // add the whole buffer to the projection buffer and set it up to expand to the right as text is appended - var promptSpan = CreatePrimaryPrompt(); - var languageSpan = new CustomTrackingSpan( - CurrentLanguageBuffer.CurrentSnapshot, - new Span(0, 0), - canAppend: true); - - // projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping: - AppendProjectionSpans(promptSpan, languageSpan); - } - - private void AppendProjectionSpans(object span1, object span2) - { - int index = _projectionBuffer.CurrentSnapshot.SpanCount; - _projectionBuffer.ReplaceSpans(index, 0, new[] { span1, span2 }, EditOptions.None, editTag: s_suppressPromptInjectionTag); - } - - private bool TryGetCurrentLanguageBufferExtent(IProjectionSnapshot projectionSnapshot, out Span result) - { - if (projectionSnapshot.SpanCount == 0) - { - result = default(Span); - return false; - } - - // the last source snapshot is always a projection of a language buffer: - var snapshot = projectionSnapshot.GetSourceSpan(projectionSnapshot.SpanCount - 1).Snapshot; - if (snapshot.TextBuffer != CurrentLanguageBuffer) - { - result = default(Span); - return false; - } - - SnapshotPoint start = new SnapshotPoint(snapshot, 0); - SnapshotPoint end = new SnapshotPoint(snapshot, snapshot.Length); - - // projection of the previous version of current language buffer snapshot: - var surfaceSpans = projectionSnapshot.MapFromSourceSnapshot(new SnapshotSpan(start, end)); - - // the language buffer might be projected to multiple surface lines: - Debug.Assert(surfaceSpans.Count > 0); - result = new Span(surfaceSpans[0].Start, surfaceSpans.Last().End); - return true; - } - - private void ProjectionBufferChanged(object sender, TextContentChangedEventArgs e) - { - // this is an edit performed in this event: - if (e.EditTag == s_suppressPromptInjectionTag) - { - return; - } - - // projection buffer is changed before language buffer is created (for example, output might be printed out during initialization): - if (CurrentLanguageBuffer == null) - { - return; - } - - var oldSnapshot = (IProjectionSnapshot)e.Before; - var newSnapshot = (IProjectionSnapshot)e.After; - Span oldSurfaceLanguageBufferExtent; - Span newSurfaceLanguageBufferExtent; - - if (!TryGetCurrentLanguageBufferExtent(oldSnapshot, out oldSurfaceLanguageBufferExtent) || - !TryGetCurrentLanguageBufferExtent(newSnapshot, out newSurfaceLanguageBufferExtent)) - { - return; - } - - List spanEdits = null; - var oldProjectionSpans = oldSnapshot.GetSourceSpans(); - int oldProjectionSpanCount = oldProjectionSpans.Count; - - // changes are sorted by position - foreach (var change in e.Changes) - { - // Old/new span might be outside of the language buffer -- on the left of it, since - // the language buffer always reaches to the end of the projection buffer. - Span oldSurfaceIntersection = oldSurfaceLanguageBufferExtent.Intersection(change.OldSpan) ?? new Span(oldSurfaceLanguageBufferExtent.Start, 0); - Span newSurfaceIntersection = newSurfaceLanguageBufferExtent.Intersection(change.NewSpan) ?? new Span(newSurfaceLanguageBufferExtent.Start, 0); - - // change doesn't affect the language buffer: - if (oldSurfaceIntersection.IsEmpty && newSurfaceIntersection.IsEmpty) - { - continue; - } - - var oldSurfaceStartLineNumber = oldSnapshot.GetLineNumberFromPosition(oldSurfaceIntersection.Start); - var oldSurfaceEndLineNumber = oldSnapshot.GetLineNumberFromPosition(oldSurfaceIntersection.End); - - // The change doesn't include line breaks and is entirely within the current - // language buffer. Note that we might need to proceed with span replacement even if - // line count delta is zero: the tracking spans of all but last language buffer - // projections need to stop growing. - if (oldSurfaceStartLineNumber == oldSurfaceEndLineNumber && - change.LineCountDelta == 0 && - oldSurfaceIntersection == change.OldSpan && - newSurfaceIntersection == change.NewSpan) - { - continue; - } - - // calculate which prompts and language projection spans to remove and replace with new spans: - int oldStartSpanIndex = GetProjectionSpanIndexFromEditableBufferPosition(oldSnapshot, oldProjectionSpanCount, oldSurfaceStartLineNumber); - int oldEndSpanIndex = GetProjectionSpanIndexFromEditableBufferPosition(oldSnapshot, oldProjectionSpanCount, oldSurfaceEndLineNumber); - - int spansToReplace = oldEndSpanIndex - oldStartSpanIndex + 1; - Debug.Assert(spansToReplace >= 1); - - var newSubjectStartLine = newSnapshot.MapToSourceSnapshot(newSurfaceIntersection.Start).GetContainingLine(); - var newSubjectEndLine = newSnapshot.MapToSourceSnapshot(newSurfaceIntersection.End).GetContainingLine(); - - var newSubjectEndLineNumber = newSubjectEndLine.LineNumber; - - int i = 0; - int lineBreakCount = newSubjectEndLineNumber - newSubjectStartLine.LineNumber; - var newSpans = new object[lineBreakCount * SpansPerLineOfInput + 1]; - - var subjectLine = newSubjectStartLine; - while (true) - { - if (subjectLine.LineNumber != newSubjectStartLine.LineNumber) - { - // TODO (crwilcox): do we need two prompts? Can I tell it to not do this? Or perhaps we do want this since we want different markings? - newSpans[i++] = CreateSecondaryPrompt(); - } - - newSpans[i++] = CreateLanguageSpanForLine(subjectLine); - - if (subjectLine.LineNumber == newSubjectEndLineNumber) - { - break; - } - - subjectLine = subjectLine.Snapshot.GetLineFromLineNumber(subjectLine.LineNumber + 1); - } - - Debug.Assert(i == newSpans.Length); - - if (spanEdits == null) - { - spanEdits = new List(); - } - - spanEdits.Add(new SpanRangeEdit(oldStartSpanIndex, spansToReplace, newSpans)); - } - - if (spanEdits != null) - { - ReplaceProjectionSpans(oldProjectionSpans, spanEdits); - } - - CheckProjectionSpans(); - } - - // Verify spans and GetSourceSpanIndex. - [Conditional("DEBUG")] - private void CheckProjectionSpans() - { - var snapshot = _projectionBuffer.CurrentSnapshot; - var sourceSpans = snapshot.GetSourceSpans(); - int n = sourceSpans.Count; - - // Spans should be contiguous and span the entire buffer. - int offset = 0; - for (int i = 0; i < n; i++) - { - // Determine the index of the first non-zero width - // span starting at the same point as current span. - int expectedIndex = i; - while (sourceSpans[expectedIndex].IsEmpty) - { - expectedIndex++; - if (expectedIndex == n) - { - break; - } - } - // Verify GetSourceSpanIndex returns the expected - // index for the start of the span. - int index = GetSourceSpanIndex(sourceSpans, new SnapshotPoint(snapshot, offset)); - Debug.Assert(index == expectedIndex); - // If this is a non-empty span, verify GetSourceSpanIndex - // returns the index for the midpoint of the span. - int length = sourceSpans[i].Length; - if (length > 0) - { - index = GetSourceSpanIndex(sourceSpans, new SnapshotPoint(snapshot, offset + length / 2)); - Debug.Assert(index == i); - } - offset += length; - } - - Debug.Assert(offset == snapshot.Length); - - if (n > 0) - { - int index = GetSourceSpanIndex(sourceSpans, new SnapshotPoint(snapshot, snapshot.Length)); - Debug.Assert(index == n); - } - } - - /// - /// This should only be called from within the current language buffer. If there are - /// any output or standard input buffers between the specified line and the end of the - /// surface buffer, then the result will be incorrect. - /// - private int GetProjectionSpanIndexFromEditableBufferPosition(IProjectionSnapshot surfaceSnapshot, int projectionSpansCount, int surfaceLineNumber) - { - // The current language buffer is projected to a set of projections interleaved regularly by prompt projections - // and ending at the end of the projection buffer, each language buffer projection is on a separate line: - // [prompt)[language)...[prompt)[language) - int result = projectionSpansCount - (surfaceSnapshot.LineCount - surfaceLineNumber) * SpansPerLineOfInput + 1; - Debug.Assert(GetSpanKind(surfaceSnapshot.GetSourceSpan(result)) == ReplSpanKind.Input); - return result; - } - - private void ReplaceProjectionSpans(ReadOnlyCollection oldProjectionSpans, List spanEdits) - { - Debug.Assert(spanEdits.Count > 0); - - int start = spanEdits[0].Start; - int end = spanEdits[spanEdits.Count - 1].End; - - var replacement = new List(); - replacement.AddRange(spanEdits[0].Replacement); - int lastEnd = spanEdits[0].End; - - for (int i = 1; i < spanEdits.Count; i++) - { - SpanRangeEdit edit = spanEdits[i]; - - int gap = edit.Start - lastEnd; - - // there is always at least prompt span in between subsequent edits - Debug.Assert(gap != 0); - - // spans can't share more then one span - Debug.Assert(gap >= -1); - - if (gap == -1) - { - replacement.AddRange(edit.Replacement.Skip(1)); - } - else - { - replacement.AddRange(oldProjectionSpans.Skip(lastEnd).Take(gap).Select(CreateTrackingSpan)); - replacement.AddRange(edit.Replacement); - } - - lastEnd = edit.End; - } - - _projectionBuffer.ReplaceSpans(start, end - start, replacement, EditOptions.None, s_suppressPromptInjectionTag); - } - - private object CreateTrackingSpan(SnapshotSpan snapshotSpan) - { - var snapshot = snapshotSpan.Snapshot; - if (snapshot.ContentType == _inertType) - { - return snapshotSpan.GetText(); - } - return new CustomTrackingSpan(snapshot, snapshotSpan.Span); - } - - private ITrackingSpan CreateLanguageSpanForLine(ITextSnapshotLine languageLine) - { - var span = languageLine.ExtentIncludingLineBreak; - bool lastLine = (languageLine.LineNumber == languageLine.Snapshot.LineCount - 1); - return new CustomTrackingSpan( - CurrentLanguageBuffer.CurrentSnapshot, - span, - canAppend: lastLine); - } - - private void ScrollToCaret() - { - var textView = TextView; - var caretPosition = textView.Caret.Position.BufferPosition; - var caretSpan = new SnapshotSpan(caretPosition.Snapshot, caretPosition, 0); - textView.ViewScroller.EnsureSpanVisible(caretSpan); - } - - private void CaretPositionChanged(object sender, CaretPositionChangedEventArgs e) - { - // make sure language buffer exist - if (CurrentLanguageBuffer == null) - { - return; - } - - var caretPoint = e.NewPosition.BufferPosition; - - // make sure caret is on the right line - // 1. changes are on virtual space - if (e.NewPosition.BufferPosition == e.OldPosition.BufferPosition) - { - return; - } - - // 2. caret is at the end of the surface line - if (caretPoint != caretPoint.GetContainingLine().End) - { - return; - } - - // 3. subject line has length == 0 - var point = e.NewPosition.Point.GetInsertionPoint(b => b == CurrentLanguageBuffer); - if (!point.HasValue) - { - return; - } - - var line = point.Value.GetContainingLine(); - if (point.Value != line.End || line.Length != 0) - { - return; - } - - try - { - // detach event handler - TextView.Caret.PositionChanged -= CaretPositionChanged; - - IndentCurrentLine(caretPoint); - } - finally - { - // attach event handler - TextView.Caret.PositionChanged += CaretPositionChanged; - } - } - - /// - /// Indents the line where the caret is currently located. - /// - /// - /// We don't send this command to the editor since smart indentation doesn't work along with - /// BufferChanged event. Instead, we need to implement indentation ourselves. We still use - /// ISmartIndentProvider provided by the language. - /// - private void IndentCurrentLine(SnapshotPoint caretPosition) - { - Debug.Assert(CurrentLanguageBuffer != null); - - var caretLine = caretPosition.GetContainingLine(); - var indentation = _smartIndenterService.GetDesiredIndentation(TextView, caretLine); - - // When the user submits via ctrl-enter, the indenter service sometimes - // gets confused and maps the subject position after the last newline in - // a language buffer to the location *before* the next prompt in the - // surface buffer. When this happens, indentation will be 0. Fortunately, - // no indentation is required in such cases, so we can just do nothing. - if (indentation != null && indentation != 0) - { - var sourceSpans = GetSourceSpans(caretPosition.Snapshot); - var promptIndex = GetPromptIndexForPoint(sourceSpans, caretPosition); - var promptSpan = sourceSpans[promptIndex]; - Debug.Assert(IsPrompt(promptSpan)); - int promptLength = promptSpan.Length; - Debug.Assert(promptLength == 2 || promptLength == 0); // Not required, just expected. - var adjustedIndentationValue = indentation.GetValueOrDefault() - promptLength; - - if (caretPosition == caretLine.End) - { - // create virtual space: - TextView.Caret.MoveTo(new VirtualSnapshotPoint(caretPosition, adjustedIndentationValue)); - } - else - { - var langCaret = GetPositionInLanguageBuffer(caretPosition); - if (langCaret == null) - { - return; - } - - // insert whitespace indentation: - var options = TextView.Options; - string whitespace = GetWhiteSpaceForVirtualSpace(adjustedIndentationValue, options.IsConvertTabsToSpacesEnabled() ? default(int?) : options.GetTabSize()); - CurrentLanguageBuffer.Insert(langCaret.Value, whitespace); - } - } - } - - private SnapshotPoint? GetPositionInLanguageBuffer(SnapshotPoint point) - { - Debug.Assert(CurrentLanguageBuffer != null); - return GetPositionInBuffer(point, CurrentLanguageBuffer); - } - - private SnapshotPoint? GetPositionInStandardInputBuffer(SnapshotPoint point) - { - Debug.Assert(StandardInputBuffer != null); - return GetPositionInBuffer(point, StandardInputBuffer); - } - - private SnapshotPoint? GetPositionInBuffer(SnapshotPoint point, ITextBuffer buffer) - { - return TextView.BufferGraph.MapDownToBuffer( - point, - PointTrackingMode.Positive, - buffer, - PositionAffinity.Successor); - } - - // Mimics EditorOperations.GetWhiteSpaceForPositionAndVirtualSpace. - private static string GetWhiteSpaceForVirtualSpace(int virtualSpaces, int? tabSize) - { - string textToInsert; - if (tabSize.HasValue) - { - int tabSizeInt = tabSize.GetValueOrDefault(); - - int spacesAfterPreviousTabStop = virtualSpaces % tabSizeInt; - int columnOfPreviousTabStop = virtualSpaces - spacesAfterPreviousTabStop; - - int requiredTabs = (columnOfPreviousTabStop + tabSizeInt - 1) / tabSizeInt; - - if (requiredTabs > 0) - { - textToInsert = new string('\t', requiredTabs) + new string(' ', spacesAfterPreviousTabStop); - } - else - { - textToInsert = new string(' ', virtualSpaces); - } - } - else - { - textToInsert = new string(' ', virtualSpaces); - } - - return textToInsert; - } - - /// Implements . - public void Cancel() - { - ClearInput(); - EditorOperations.MoveToEndOfDocument(false); - _uncommittedInput = null; - _historySearch = null; - } - - private void ClearInput() - { - if (ReadingStandardInput) - { - StandardInputBuffer.Delete(GetStandardInputSpan()); - } - else - { - CurrentLanguageBuffer.Delete(new Span(0, CurrentLanguageBuffer.CurrentSnapshot.Length)); - } - } - - /// Implements . - public void HistoryPrevious(string search) - { - if (CurrentLanguageBuffer == null) - { - return; - } - - var previous = _history.GetPrevious(search); - if (previous != null) - { - if (string.IsNullOrWhiteSpace(search)) - { - // don't store search as an uncommitted history item - StoreUncommittedInputForHistory(); - } - - SetActiveCodeToHistory(previous); - EditorOperations.MoveToEndOfDocument(false); - } - } - - /// Implements . - public void HistoryNext(string search) - { - if (CurrentLanguageBuffer == null) - { - return; - } - - var next = _history.GetNext(search); - if (next != null) - { - if (string.IsNullOrWhiteSpace(search)) - { - // don't store search as an uncommitted history item - StoreUncommittedInputForHistory(); - } - - SetActiveCodeToHistory(next); - EditorOperations.MoveToEndOfDocument(false); - } - else - { - string code = _history.UncommittedInput; - _history.UncommittedInput = null; - if (!string.IsNullOrEmpty(code)) - { - SetActiveCode(code); - EditorOperations.MoveToEndOfDocument(false); - } - } - } - - /// - /// Sets the active code to the specified history entry. - /// - /// - private void SetActiveCodeToHistory(History.Entry entry) - { - SetActiveCode(entry.Text); - } - - /// - /// Sets the active code to the specified text w/o executing it. - /// - private void SetActiveCode(string text) - { - // TODO (tomat): this should be handled by the language intellisense provider, not here: - var completionSession = SessionStack.TopSession; - if (completionSession != null) - { - completionSession.Dismiss(); - } - - using (var edit = CurrentLanguageBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, editTag: null)) - { - edit.Replace(new Span(0, CurrentLanguageBuffer.CurrentSnapshot.Length), text); - edit.Apply(); - } - } - - /// Implements . - public void HistorySearchNext() - { - EnsureHistorySearch(); - HistoryNext(_historySearch); - } - - /// Implements . - public void HistorySearchPrevious() - { - EnsureHistorySearch(); - HistoryPrevious(_historySearch); - } - - private void EnsureHistorySearch() - { - if (_historySearch == null) - { - _historySearch = CurrentLanguageBuffer.CurrentSnapshot.GetText(); - } - } - - private void StoreUncommittedInputForHistory() - { - if (_history.UncommittedInput == null) - { - string activeCode = GetActiveCode(); - // save uncommitted input for history even if it is empty else - // on the next history navigation the previous history entry would - // be saved as uncommitted input, which we do not want. Uncommitted - // input is to save what ever user has typed and storing empty string - // when he hasn't typed anything does no harm. - _history.UncommittedInput = activeCode; - } - } - - /// - /// Maps projectionBufferPoint down to first matching source buffer. - /// - /// Must be a point in projectin buffer - private SnapshotPoint GetSourceBufferPoint(SnapshotPoint projectionBufferPoint) - { - Debug.Assert(projectionBufferPoint.Snapshot.TextBuffer == _projectionBuffer); - - return TextView.BufferGraph.MapDownToFirstMatch( - projectionBufferPoint, - PointTrackingMode.Positive, - snapshot => snapshot.TextBuffer != _projectionBuffer, - PositionAffinity.Successor).Value; - } - - /// - /// Maps sourceBufferPoint up to projection buffer. - /// - private SnapshotPoint GetProjectionBufferPoint(SnapshotPoint sourceBufferPoint) - { - Debug.Assert(sourceBufferPoint.Snapshot.TextBuffer != _projectionBuffer); - - return TextView.BufferGraph.MapUpToBuffer( - sourceBufferPoint, - PointTrackingMode.Positive, - PositionAffinity.Successor, - _projectionBuffer).Value; - } - - /// - /// Moves to the beginning of the line. - /// Implements . - /// - public void Home(bool extendSelection) - { - var caret = TextView.Caret; - - // map the end of subject buffer line: - var subjectLineEnd = TextView.BufferGraph.MapDownToFirstMatch( - caret.Position.BufferPosition.GetContainingLine().End, - PointTrackingMode.Positive, - snapshot => snapshot.TextBuffer != _projectionBuffer, - PositionAffinity.Successor).Value; - - ITextSnapshotLine subjectLine = subjectLineEnd.GetContainingLine(); - - var projectedSubjectLineStart = TextView.BufferGraph.MapUpToBuffer( - subjectLine.Start, - PointTrackingMode.Positive, - PositionAffinity.Successor, - _projectionBuffer).Value; - - // If the caret is already at the first non-whitespace character or the line is - // entirely whitespace, move to the start of the view line. See - // (EditorOperations.MoveToHome). - // - // If the caret is in the prompt move the caret to the beginning of the language - // line. - - int firstNonWhiteSpace = IndexOfNonWhiteSpaceCharacter(subjectLine); - SnapshotPoint moveTo; - if (firstNonWhiteSpace == -1 || - projectedSubjectLineStart.Position + firstNonWhiteSpace == caret.Position.BufferPosition || - caret.Position.BufferPosition < projectedSubjectLineStart.Position) - { - moveTo = projectedSubjectLineStart; - } - else - { - moveTo = projectedSubjectLineStart + firstNonWhiteSpace; - } - - if (extendSelection) - { - VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint; - caret.MoveTo(moveTo); - TextView.Selection.Select(anchor.TranslateTo(TextView.TextSnapshot), TextView.Caret.Position.VirtualBufferPosition); - } - else - { - TextView.Selection.Clear(); - caret.MoveTo(moveTo); - } - caret.EnsureVisible(); - } - - /// - /// Moves to the end of the line. - /// Implements . - /// - public void End(bool extendSelection) - { - var caret = TextView.Caret; - - // map the end of the subject buffer line: - var subjectLineEnd = TextView.BufferGraph.MapDownToFirstMatch( - caret.Position.BufferPosition.GetContainingLine().End, - PointTrackingMode.Positive, - snapshot => snapshot.TextBuffer != _projectionBuffer, - PositionAffinity.Successor).Value; - - ITextSnapshotLine subjectLine = subjectLineEnd.GetContainingLine(); - - var moveTo = TextView.BufferGraph.MapUpToBuffer( - subjectLine.End, - PointTrackingMode.Positive, - PositionAffinity.Successor, - _projectionBuffer).Value; - - if (extendSelection) - { - VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint; - caret.MoveTo(moveTo); - TextView.Selection.Select(anchor.TranslateTo(TextView.TextSnapshot), TextView.Caret.Position.VirtualBufferPosition); - } - else - { - TextView.Selection.Clear(); - caret.MoveTo(moveTo); - } - caret.EnsureVisible(); - } - - /// Implements . - public void SelectAll() - { - SnapshotSpan? span = GetContainingRegion(TextView.Caret.Position.BufferPosition); - - var selection = TextView.Selection; - - // if the span is already selected select all text in the projection buffer: - if (span == null || - !selection.IsEmpty && selection.SelectedSpans.Count == 1 && selection.SelectedSpans[0] == span.Value) - { - var currentSnapshot = TextView.TextBuffer.CurrentSnapshot; - span = new SnapshotSpan(currentSnapshot, new Span(0, currentSnapshot.Length)); - } - - selection.Select(span.Value, isReversed: false); - // SelectAll always returns stream selection - selection.Mode = TextSelectionMode.Stream; - } - - /// - /// Given a point in projection buffer calculate a span that includes the point and comprises of - /// subsequent projection spans forming a region, i.e. a sequence of output spans in between two subsequent submissions, - /// a language input block, or standard input block. - /// - private SnapshotSpan? GetContainingRegion(SnapshotPoint point) - { - var sourceSpans = GetSourceSpans(point.Snapshot); - int promptIndex = GetPromptIndexForPoint(sourceSpans, point); - if (promptIndex < 0) - { - return null; - } - - // Grab the span following the prompt (either language or standard input). - var projectionSpan = sourceSpans[promptIndex + 1]; - var inputSnapshot = projectionSpan.Snapshot; - var kind = GetSpanKind(projectionSpan); - - Debug.Assert(kind == ReplSpanKind.Input || kind == ReplSpanKind.StandardInput); - - // Language input block is a projection of the entire snapshot; - // std input block is a projection of a single span: - SnapshotPoint inputBufferEnd = (kind == ReplSpanKind.Input) ? - new SnapshotPoint(inputSnapshot, inputSnapshot.Length) : - projectionSpan.End; - - var bufferGraph = TextView.BufferGraph; - var textBuffer = TextView.TextBuffer; - - SnapshotPoint projectedInputBufferEnd = bufferGraph.MapUpToBuffer( - inputBufferEnd, - PointTrackingMode.Positive, - PositionAffinity.Predecessor, - textBuffer).Value; - - // point is between the primary prompt (including) and the last character of the corresponding language/stdin buffer: - if (point <= projectedInputBufferEnd) - { - var projectedLanguageBufferStart = bufferGraph.MapUpToBuffer( - new SnapshotPoint(inputSnapshot, 0), - PointTrackingMode.Positive, - PositionAffinity.Successor, - textBuffer).Value; - - var promptProjectionSpan = sourceSpans[promptIndex]; - if (point < projectedLanguageBufferStart - promptProjectionSpan.Length) - { - // cursor is before the first language buffer: - return new SnapshotSpan(new SnapshotPoint(textBuffer.CurrentSnapshot, 0), projectedLanguageBufferStart - promptProjectionSpan.Length); - } - - // cursor is within the language buffer: - return new SnapshotSpan(projectedLanguageBufferStart, projectedInputBufferEnd); - } - - int nextPromptIndex = -1; - for (int i = promptIndex + 1; i < sourceSpans.Count; i++) - { - if (IsPrompt(sourceSpans[i])) - { - nextPromptIndex = i; - break; - } - } - - // this was the last primary/stdin prompt - select the part of the projection buffer behind the end of the language/stdin buffer: - if (nextPromptIndex < 0) - { - var currentSnapshot = textBuffer.CurrentSnapshot; - return new SnapshotSpan( - projectedInputBufferEnd, - new SnapshotPoint(currentSnapshot, currentSnapshot.Length)); - } - - var lastSpanBeforeNextPrompt = sourceSpans[nextPromptIndex - 1]; - Debug.Assert(GetSpanKind(lastSpanBeforeNextPrompt) == ReplSpanKind.Output); - - // select all text in between the language buffer and the next prompt: - return new SnapshotSpan( - projectedInputBufferEnd, - bufferGraph.MapUpToBuffer( - lastSpanBeforeNextPrompt.End, - PointTrackingMode.Positive, - PositionAffinity.Predecessor, - textBuffer).Value); - } - private bool IsEmptyBoxSelection() - { - return !TextView.Selection.IsEmpty && - TextView.Selection.VirtualSelectedSpans.All(s => s.IsEmpty); - } - - private bool ReduceBoxSelectionToEditableBox(bool isDelete = true) - { - Debug.Assert(TextView.Selection.Mode == TextSelectionMode.Box); - - VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint; - VirtualSnapshotPoint active = TextView.Selection.ActivePoint; - - bool result; - if (active < anchor) - { - result = ReduceBoxSelectionToEditableBox(ref active, ref anchor, isDelete); - } - else - { - result = ReduceBoxSelectionToEditableBox(ref anchor, ref active, isDelete); - } - - TextView.Selection.Select(anchor, active); - TextView.Caret.MoveTo(active); - - return result; - } - - private bool ReduceBoxSelectionToEditableBox(ref VirtualSnapshotPoint selectionTop, ref VirtualSnapshotPoint selectionBottom, bool isDelete) - { - int selectionTopColumn, selectionBottomColumn; - ITextSnapshotLine selectionTopLine, selectionBottomLine; - selectionTop.GetLineAndColumn(out selectionTopLine, out selectionTopColumn); - selectionBottom.GetLineAndColumn(out selectionBottomLine, out selectionBottomColumn); - - int selectionLeftColumn, selectionRightColumn; - bool horizontallyReversed = selectionTopColumn > selectionBottomColumn; - - if (horizontallyReversed) - { - // bottom-left <-> top-right - selectionLeftColumn = selectionBottomColumn; - selectionRightColumn = selectionTopColumn; - } - else - { - // top-left <-> bottom-right - selectionLeftColumn = selectionTopColumn; - selectionRightColumn = selectionBottomColumn; - } - - var selectionTopLeft = new VirtualSnapshotPoint(selectionTopLine, selectionLeftColumn); - var selectionBottomRight = new VirtualSnapshotPoint(selectionBottomLine, selectionRightColumn); - - SnapshotPoint editable = GetClosestEditablePoint(selectionTopLeft.Position); - int editableColumn; - ITextSnapshotLine editableLine; - editable.GetLineAndColumn(out editableLine, out editableColumn); - - Debug.Assert(selectionLeftColumn <= selectionRightColumn); - Debug.Assert(selectionTopLine.LineNumber <= selectionBottomLine.LineNumber); - - if (editable > selectionBottomRight.Position) - { - // entirely within readonly output region: - return false; - } - - int minPromptLength, maxPromptLength; - if (ReadingStandardInput) - { - minPromptLength = maxPromptLength = 0; - } - else - { - MeasurePrompts(editableLine.LineNumber, selectionBottomLine.LineNumber + 1, out minPromptLength, out maxPromptLength); - } - - bool result = true; - if (isDelete) - { - if (selectionLeftColumn > maxPromptLength || maxPromptLength == minPromptLength) - { - selectionTopLine = editableLine; - selectionLeftColumn = Math.Max(selectionLeftColumn, maxPromptLength); - } - } - else - { - if (selectionRightColumn < minPromptLength) - { - // entirely within readonly prompt region: - result = false; - } - else if (maxPromptLength > selectionRightColumn) - { - selectionTopLine = editableLine; - selectionLeftColumn = maxPromptLength; - selectionRightColumn = maxPromptLength; - } - else - { - selectionTopLine = editableLine; - selectionLeftColumn = Math.Max(maxPromptLength, selectionLeftColumn); - } - } - - if (horizontallyReversed) - { - // bottom-left <-> top-right - selectionTop = new VirtualSnapshotPoint(selectionTopLine, selectionRightColumn); - selectionBottom = new VirtualSnapshotPoint(selectionBottomLine, selectionLeftColumn); - } - else - { - // top-left <-> bottom-right - selectionTop = new VirtualSnapshotPoint(selectionTopLine, selectionLeftColumn); - selectionBottom = new VirtualSnapshotPoint(selectionBottomLine, selectionRightColumn); - } - - return result; - } - - /// - /// Returns the lengths of the longest and shortest prompts within the specified range of lines of the current submission buffer. - /// - private void MeasurePrompts(int startLine, int endLine, out int minPromptLength, out int maxPromptLength) - { - Debug.Assert(endLine > startLine); - - var projectionSnapshot = _projectionBuffer.CurrentSnapshot; - var sourceSpans = projectionSnapshot.GetSourceSpans(); - var promptSpanIndex = GetProjectionSpanIndexFromEditableBufferPosition(projectionSnapshot, sourceSpans.Count, startLine) - 1; - var promptSpan = sourceSpans[promptSpanIndex]; - Debug.Assert(IsPrompt(promptSpan)); - - minPromptLength = maxPromptLength = promptSpan.Length; - } - - /// Implements . - public bool Backspace() - { - using (var transaction = UndoHistory?.CreateTransaction(InteractiveWindowResources.Backspace)) - { - if (DeleteHelper(isBackspace: true)) - { - transaction?.Complete(); - return true; - } - } - return false; - } - - /// - /// Implements . - /// `Delete` will not delete anything if any part of the selection is not in - /// current submission (input or active prompts). - /// - public bool Delete() - { - _historySearch = null; - using (var transaction = UndoHistory?.CreateTransaction(InteractiveWindowResources.Delete)) - { - if (DeleteHelper(isBackspace: false)) - { - transaction?.Complete(); - return true; - } - } - return false; - } - - private bool DeleteHelper(bool isBackspace) - { - var selection = TextView.Selection; - - if (!selection.IsEmpty) - { - // do not delete anything if any part of selection is not in current submission - if (!IsSelectionInsideCurrentSubmission()) - { - return false; - } - - if (IsEmptyBoxSelection()) - { - return isBackspace ? EditorOperations.Backspace() : EditorOperations.Delete(); - } - - DeleteSelection(); - - if (selection.Mode == TextSelectionMode.Box) - { - ReduceBoxSelectionToEditableBox(isDelete: true); - } - else - { - selection.Clear(); - MoveCaretToClosestEditableBuffer(); - } - TextView.Caret.EnsureVisible(); - return true; - } - else if (TextView.Caret.Position.VirtualSpaces == 0) - { - if (IsInActivePrompt(TextView.Caret.Position.BufferPosition)) - { - MoveCaretToClosestEditableBuffer(); - } - return isBackspace ? DeletePreviousCharacter() : DeleteNextCharacter(); - } - else - { - if (isBackspace) - { - TextView.Caret.MoveToPreviousCaretPosition(); - } - else - { - TextView.Caret.MoveToNextCaretPosition(); - } - return true; - } - } - - /// Implements . - public void DeleteLine() - { - _historySearch = null; - CutLineOrDeleteLineHelper(isCut: false); - } - - /// Implements . - public void CutLine() - { - _historySearch = null; - CutLineOrDeleteLineHelper(isCut: true); - } - - /// Cut/Delete all selected lines, or the current line if no selection. - private void CutLineOrDeleteLineHelper(bool isCut) - { - using (var transaction = UndoHistory?.CreateTransaction(isCut ? InteractiveWindowResources.CutLine : InteractiveWindowResources.DeleteLine)) - { - if (TextView.Selection.IsEmpty) - { - if (isCut) - { - CopyCurrentLine(); - } - if (!DeleteCurrentLine()) - { - return; - } - TextView.Caret.MoveTo(TextView.Caret.Position.BufferPosition.GetContainingLine().Start); - } - else - { - var projectionSpans = CopySelectedLines(); - if (!IsSpanCollectionInsideCurrentSubmission(projectionSpans)) - { - return; - } - DeleteSpans(projectionSpans); - TextView.Selection.Clear(); - } - MoveCaretToClosestEditableBuffer(); - TextView.Caret.EnsureVisible(); - - transaction?.Complete(); - } - } - - /// - /// Returns true if the entire selection is inside current submission. - /// Current submission includes all active prompt buffers and all editable buffers - /// - private bool IsSelectionInsideCurrentSubmission() - { - var selection = TextView.Selection; - Debug.Assert(!selection.IsEmpty); - return IsSpanCollectionInsideCurrentSubmission(selection.SelectedSpans); - } - - private bool IsSpanCollectionInsideCurrentSubmission(NormalizedSnapshotSpanCollection spans) - { - foreach (var span in spans) - { - var currentLine = span.Start.GetContainingLine(); - var end = currentLine.End; - if (MapToEditableBuffer(end) == null) - { - return false; - } - } - return true; - } - - private bool DeleteSelection() - { - var selection = TextView.Selection; - - if (selection.IsEmpty || !IsSelectionInsideCurrentSubmission()) - { - return false; - } - - DeleteSpans(selection.SelectedSpans); - return true; - } - - /// - /// Delete the line where the caret is located, if the line is a part of current submission. - /// - private bool DeleteCurrentLine() - { - Debug.Assert(TextView.Selection.IsEmpty); - var line = TextView.Caret.Position.BufferPosition.GetContainingLine(); - // the caret is located in a line with only readonly content - // (i.e. output line or previously submitted input line) - if (MapToEditableBuffer(line.End) == null) - { - return false; - } - - DeleteSpans(new NormalizedSnapshotSpanCollection(line.ExtentIncludingLineBreak)); - return true; - } - - /// - /// Delete spans that lie in editable buffer from given spans. - /// This method keeps selection and caret position intact, - /// therefore it's caller's responsibility to adjust them accordingly. - /// - private void DeleteSpans(NormalizedSnapshotSpanCollection projectionSpans) - { - // split into multiple deletes that only affect the language/input buffer: - ITextBuffer affectedBuffer = (ReadingStandardInput) ? StandardInputBuffer : CurrentLanguageBuffer; - using (var edit = affectedBuffer.CreateEdit()) - { - foreach (var projectionSpan in projectionSpans) - { - var spans = TextView.BufferGraph.MapDownToBuffer(projectionSpan, SpanTrackingMode.EdgeInclusive, affectedBuffer); - foreach (var span in spans) - { - edit.Delete(span); - } - } - edit.Apply(); - } - } - - /// - /// Pastes from the clipboard into the text view - /// Implements . - /// - public bool Paste() - { - bool dataHasLineCutCopyTag = false; - bool dataHasBoxCutCopyTag = false; - - // Get text from clipboard - string code = Evaluator.FormatClipboard(); - if (code == null) - { - var data = _window.InteractiveWindowClipboard.GetDataObject(); - if (data == null) - { - return false; - } - - dataHasLineCutCopyTag = data.GetDataPresent(ClipboardLineBasedCutCopyTag); - dataHasBoxCutCopyTag = data.GetDataPresent(BoxSelectionCutCopyTag); - - Debug.Assert((dataHasLineCutCopyTag && dataHasBoxCutCopyTag) == false); - - if (_window.InteractiveWindowClipboard.ContainsData(InteractiveClipboardFormat.Tag)) - { - var sb = new StringBuilder(); - var blocks = BufferBlock.Deserialize((string)_window.InteractiveWindowClipboard.GetData(InteractiveClipboardFormat.Tag)); - - foreach (var block in blocks) - { - switch (block.Kind) - { - // the actual linebreak was converted to regular Input when copied - // This LineBreak block was created by coping box selection and is used as line separater when pasted - case ReplSpanKind.LineBreak: - Debug.Assert(dataHasBoxCutCopyTag); - sb.Append(block.Content); - break; - case ReplSpanKind.Input: - case ReplSpanKind.Output: - case ReplSpanKind.StandardInput: - sb.Append(block.Content); - break; - } - } - code = sb.ToString(); - } - else if (_window.InteractiveWindowClipboard.ContainsText()) - { - code = _window.InteractiveWindowClipboard.GetText(); - } - else - { - return false; - } - } - - using (var transaction = UndoHistory?.CreateTransaction(InteractiveWindowResources.Paste)) - { - var selection = TextView.Selection; - - // Delete selected text if there's any and adjust caret position - if (!selection.IsEmpty) - { - // do not delete and paste anything if any part of selection is not in current submission - if (!IsSelectionInsideCurrentSubmission()) - { - return false; - } - - DeleteSelection(); - - if (selection.Mode == TextSelectionMode.Box) - { - ReduceBoxSelectionToEditableBox(isDelete: true); - } - else - { - selection.Clear(); - MoveCaretToClosestEditableBuffer(); - } - } - else - { - var caretPosition = TextView.Caret.Position.BufferPosition; - var isInActivePrompt = IsInActivePrompt(caretPosition); - - if (isInActivePrompt) - { - MoveCaretToClosestEditableBuffer(); - } - else if (MapToEditableBuffer(caretPosition) == null) - { - return false; - } - - // Move caret to the begining of the line for pasting full-line when selection is empty - // If the caret was in active prompt, it was already moved to strat of input line - if (dataHasLineCutCopyTag && !isInActivePrompt) - { - var endPoint = GetSourceBufferPoint(caretPosition.GetContainingLine().End); - TextView.Caret.MoveTo(GetProjectionBufferPoint(endPoint.GetContainingLine().Start)); - } - } - - if (dataHasBoxCutCopyTag) - { - if (selection.IsEmpty && IsCaretOnBlankEditableLine()) - { - InsertText(code); - } - else - { - VirtualSnapshotPoint unusedStart, unusedEnd; - EditorOperations.InsertTextAsBox(code, out unusedStart, out unusedEnd); - } - } - else - { - InsertText(code); - } - - transaction?.Complete(); - return true; - } - } - - /// - /// Implements . - /// Cut is logically expressed as a combination of Copy and Delete. - /// i.e. it always copies entire selection, but will not delete anything - /// if any part of the selection is not in current submission (input or active prompts) - /// /// - public void Cut() - { - using (var transaction = UndoHistory?.CreateTransaction(InteractiveWindowResources.Cut)) - { - if (TextView.Selection.IsEmpty) - { - CopyCurrentLine(); - if (!DeleteCurrentLine()) - { - return; - } - MoveCaretToClosestEditableBuffer(); - } - else - { - var selection = TextView.Selection; - CopySelection(); - if (!DeleteSelection()) - { - return; - } - - if (selection.Mode == TextSelectionMode.Box) - { - ReduceBoxSelectionToEditableBox(isDelete: true); - } - else - { - selection.Clear(); - MoveCaretToClosestEditableBuffer(); - } - TextView.Caret.EnsureVisible(); - } - - transaction?.Complete(); - } - } - - /// Implements . - public void Copy() - { - if (TextView.Selection.IsEmpty) - { - CopyCurrentLine(); - } - else - { - CopySelection(); - } - } - - /// Implements . - public void CopyCode() - { - var selection = TextView.Selection; - NormalizedSnapshotSpanCollection spans; - if (selection.IsEmpty) - { - spans = GetSpansFromCurrentLine(); - } - else - { - spans = selection.SelectedSpans; - } - - var inputSpans = new List(); - foreach (var span in spans) - { - // For each selected source buffer span, if the span is in input buffer, - // the lambda function generates the corresponding snapshot span in the source buffer snapshot, otherwise it returns null. - GetValuesFromSpan(inputSpans, - span, - (kind, snapshot, s) => kind == ReplSpanKind.Input ? new SnapshotSpan(snapshot, s) : (SnapshotSpan?)null); - } - var projectionInputSpans = new List(); - foreach (var inputSpan in inputSpans) - { - projectionInputSpans.AddRange(TextView.BufferGraph.MapUpToSnapshot(inputSpan, SpanTrackingMode.EdgeInclusive, _projectionBuffer.CurrentSnapshot)); - } - var projectSpans = new NormalizedSnapshotSpanCollection(projectionInputSpans); - CopySpans(projectSpans, lineCutCopyTag: selection.IsEmpty, boxCutCopyTag: !selection.IsEmpty && selection.Mode == TextSelectionMode.Box); - } - - private void CopySelection() - { - Debug.Assert(!TextView.Selection.IsEmpty); - - CopySpans(TextView.Selection.SelectedSpans, lineCutCopyTag: false, boxCutCopyTag: TextView.Selection.Mode == TextSelectionMode.Box); - } - - private void CopyCurrentLine() - { - Debug.Assert(TextView.Selection.IsEmpty); - CopySpans(GetSpansFromCurrentLine(), lineCutCopyTag: true, boxCutCopyTag: false); - } - - private NormalizedSnapshotSpanCollection GetSpansFromCurrentLine() - { - var snapshotLine = TextView.Caret.Position.VirtualBufferPosition.Position.GetContainingLine(); - var span = new SnapshotSpan(snapshotLine.Start, snapshotLine.LengthIncludingLineBreak); - return new NormalizedSnapshotSpanCollection(span); - } - - private NormalizedSnapshotSpanCollection CopySelectedLines() - { - Debug.Assert(!TextView.Selection.IsEmpty); - var selectedLines = GetSpansFromSelectedLines(); - CopySpans(selectedLines, lineCutCopyTag: true, boxCutCopyTag: false); - return selectedLines; - } - - private NormalizedSnapshotSpanCollection GetSpansFromSelectedLines() - { - var selection = TextView.Selection; - var startPoint = selection.Start.Position.GetContainingLine().Start; - var projectionSpans = TextView.BufferGraph.MapUpToSnapshot(new SnapshotSpan(startPoint, - selection.End.Position.GetContainingLine().EndIncludingLineBreak), - SpanTrackingMode.EdgeInclusive, - _projectionBuffer.CurrentSnapshot); - return projectionSpans; - } - - /// - /// Copy contetnt of given spans. - /// - copy with style for RTF format. - /// - copy without style for other text formats. - /// - copy each block with buffer info into a costum InteractiveWindow format. - /// This allows paste into code editors of just the code and paste of the entire content for editors that support RTF. - /// - private void CopySpans(NormalizedSnapshotSpanCollection spans, bool lineCutCopyTag, bool boxCutCopyTag) - { - if (spans == NormalizedSnapshotSpanCollection.Empty) - { - return; - } - - var data = new DataObject(); - - var text = GetText(spans, boxCutCopyTag); - data.SetData(DataFormats.Text, text); - data.SetData(DataFormats.StringFormat, text); - data.SetData(DataFormats.UnicodeText, text); - - var blocks = GetTextBlocks(spans, boxCutCopyTag); - data.SetData(InteractiveClipboardFormat.Tag, blocks); - - string rtf = null; - try - { - rtf = GenerateRtf(spans, boxCutCopyTag); - } - catch (OperationCanceledException) - { - // Ignore cancellation when doing a copy. The user may not even want RTF text - // so preventing the normal text from being copied would be overkill. - } - if (rtf != null) - { - data.SetData(DataFormats.Rtf, rtf); - } - - //tag the data in the clipboard if requested - if (lineCutCopyTag) - { - data.SetData(ClipboardLineBasedCutCopyTag, true); - } - - if (boxCutCopyTag) - { - data.SetData(BoxSelectionCutCopyTag, true); - } - - _window.InteractiveWindowClipboard.SetDataObject(data, true); - } - - private string GenerateRtf(NormalizedSnapshotSpanCollection spans, bool isBoxSelection) - { - // This behavior is consistent with VS editor. - // Don't generate RTF for large spans (since it is expensive and probably not wanted). - int length = spans.Sum((span) => span.Length); - if (length < 1000000) - { - using (var dialog = _waitIndicator.StartWait(InteractiveWindowResources.WaitTitle, InteractiveWindowResources.WaitMessage, allowCancel: true)) - { - return isBoxSelection - ? _rtfBuilderService.GenerateRtf(spans, dialog.CancellationToken) - : _rtfBuilderService.GenerateRtf(spans, string.Empty, dialog.CancellationToken); - } - } - else - { - return null; - } - } - - /// - /// Get the text of the given spans. - /// If there are multiple spans, then returns either concatenation of text from each span or concatenation of text plus a newline character, - /// depends on whether the multiple spans is because box selection. Otherwise, simply returns the text of the only span. - /// - private string GetText(NormalizedSnapshotSpanCollection spans, bool isBoxSelection) - { - Debug.Assert(spans.Count > 0); - - if (spans.Count > 1) - { - var newline = EditorOperations.Options.GetNewLineCharacter(); - var builder = new StringBuilder(); - foreach (var span in spans) - { - builder.Append(span.GetText()); - - // If spans are got from box selection, add a newline after each span. - if (isBoxSelection) - { - builder.Append(newline); - } - } - return builder.ToString(); - } - else - { - return spans[0].GetText(); - } - } - - /// - /// Get the text of the given spans as a serialized BufferBlock[]. - /// - private string GetTextBlocks(NormalizedSnapshotSpanCollection spans, bool isBoxSelection) - { - var blocks = new List(); - foreach (var span in spans) - { - // The lambda function generates a BufferBlock for each selected source buffer span - GetValuesFromSpan(blocks, span, (kind, snapshot, s) => - { - if (kind == ReplSpanKind.LineBreak) - { - kind = ReplSpanKind.Output; - } - - return new BufferBlock(kind, snapshot.GetText(s)); - }); - - // If spans are got from box selection, we use 'LineBreak' block to separate different lines of box selection. - if (isBoxSelection) - { - blocks.Add(new BufferBlock(ReplSpanKind.LineBreak, EditorOperations.Options.GetNewLineCharacter())); - } - } - return BufferBlock.Serialize(blocks.ToArray()); - } - - /// - /// Maps given snapshot span into a list of spans in source buffers, and let the user provided delegate generates an object of type T - /// for each span and added it to the list if it is not null. - /// - private void GetValuesFromSpan(List list, SnapshotSpan span, Func generateValue) - where T : struct - { - // Find the range of source spans that cover the span. - var sourceSpans = GetSourceSpans(span.Snapshot); - int n = sourceSpans.Count; - int index = GetSourceSpanIndex(sourceSpans, span.Start); - if (index == n) - { - index--; - } - - for (; index < n; index++) - { - var sourceSpan = sourceSpans[index]; - if (sourceSpan.IsEmpty) - { - continue; - } - var sourceSnapshot = sourceSpan.Snapshot; - var mappedSpans = TextView.BufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeExclusive, sourceSnapshot.TextBuffer); - bool added = false; - foreach (var mappedSpan in mappedSpans) - { - var intersection = sourceSpan.Span.Intersection(mappedSpan); - if (intersection.HasValue && !intersection.Value.IsEmpty) - { - var kind = GetSpanKind(sourceSpan); - var interactionValue = intersection.Value; - var content = sourceSnapshot.GetText(interactionValue); - - var TValue = generateValue(kind, sourceSnapshot, interactionValue); - if (TValue.HasValue) - { - list.Add(TValue.Value); - } - added = true; - } - } - if (!added) - { - break; - } - } - } - - /// - /// Deletes characters preceding the current caret position in the current language buffer. - /// - /// Returns true if the previous character was deleted - /// - private bool DeletePreviousCharacter() - { - SnapshotPoint? point = MapToEditableBuffer(TextView.Caret.Position.BufferPosition); - - // We are not in an editable buffer, or we are at the start of the buffer, nothing to delete. - if (point == null || point.Value == 0) - { - return false; - } - - var line = point.Value.GetContainingLine(); - int characterSize; - if (line.Start.Position == point.Value.Position) - { - Debug.Assert(line.LineNumber != 0); - characterSize = line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1).LineBreakLength; - } - else - { - characterSize = 1; - } - - point.Value.Snapshot.TextBuffer.Delete(new Span(point.Value.Position - characterSize, characterSize)); - - ScrollToCaret(); - return true; - } - - /// - /// Deletes characters succeeding the current caret position in the current language buffer. - /// - /// Returns true if the next character was deleted - /// - private bool DeleteNextCharacter() - { - SnapshotPoint? point = MapToEditableBuffer(TextView.Caret.Position.BufferPosition); - - // We are not in an editable buffer, or we are at the end of the buffer, nothing to delete. - if (point == null || point.Value == point.Value.Snapshot.Length) - { - return false; - } - - var pointValue = point.GetValueOrDefault(); - - var line = pointValue.GetContainingLine(); - int characterSize; - if (line.End.Position == pointValue.Position) - { - Debug.Assert(line.LineNumber != pointValue.Snapshot.LineCount); - characterSize = line.Snapshot.GetLineFromLineNumber(line.LineNumber).LineBreakLength; - } - else - { - characterSize = 1; - } - - pointValue.Snapshot.TextBuffer.Delete(new Span(pointValue.Position, characterSize)); - - ScrollToCaret(); - return true; - } - - /// - /// Maps point to the current language buffer or editable region of standard input buffer. - /// - private SnapshotPoint? MapToEditableBuffer(SnapshotPoint projectionPoint) - { - SnapshotPoint? result = null; - - if (CurrentLanguageBuffer != null) - { - result = GetPositionInLanguageBuffer(projectionPoint); - } - - if (result != null) - { - return result; - } - - if (StandardInputBuffer != null && InStandardInputRegion(projectionPoint)) - { - result = GetPositionInStandardInputBuffer(projectionPoint); - } - - return result; - } - - /// Implements . - public bool TrySubmitStandardInput() - { - _historySearch = null; - if (ReadingStandardInput) - { - if (InStandardInputRegion(TextView.Caret.Position.BufferPosition)) - { - SubmitStandardInput(); - } - - return true; - } - - return false; - } - - private void SubmitStandardInput() - { - AppendLineNoPromptInjection(StandardInputBuffer); - var inputSpan = new SnapshotSpan(StandardInputBuffer.CurrentSnapshot, GetStandardInputSpan()); - _history.Add(inputSpan); - SetStandardInputValue(inputSpan); - - MakeStandardInputReadonly(); - - // Subsequent input should appear after the input span we just finished. - NewOutputBuffer(); - - if (State == State.WaitingForInputAndReadingStandardInput) - { - PrepareForInput(); // Will update State. - } - else - { - State = GetStateBeforeReadingStandardInput(State); - } - } - - private bool InStandardInputRegion(SnapshotPoint point) - { - if (!ReadingStandardInput) - { - return false; - } - - var standardInputPoint = GetPositionInStandardInputBuffer(point); - if (!standardInputPoint.HasValue) - { - return false; - } - - var standardInputPosition = standardInputPoint.GetValueOrDefault().Position; - var standardInputSpan = GetStandardInputSpan(); - return standardInputSpan.Contains(standardInputPosition) || standardInputSpan.End == standardInputPosition; - } - - /// - /// Add a zero-width tracking span at the end of the projection buffer mapping to the end of the standard input buffer. - /// - private void AddStandardInputSpan() - { - var promptSpan = CreateStandardInputPrompt(); - var currentSnapshot = StandardInputBuffer.CurrentSnapshot; - var inputSpan = new CustomTrackingSpan( - currentSnapshot, - new Span(currentSnapshot.Length, 0), - canAppend: true); - AppendProjectionSpans(promptSpan, inputSpan); - } - - /// Implements . - public bool BreakLine() - { - using (var transaction = UndoHistory?.CreateTransaction(InteractiveWindowResources.BreakLine)) - { - if (HandlePostServicesReturn(false)) - { - transaction?.Complete(); - return true; - } - } - return false; - } - - /// Implements . - public bool Return() - { - _historySearch = null; - return HandlePostServicesReturn(true); - } - - private bool HandlePostServicesReturn(bool trySubmit) - { - if (CurrentLanguageBuffer == null) - { - return false; - } - - var selection = TextView.Selection; - if (!TextView.Selection.IsEmpty) - { - if (IsSelectionInsideCurrentSubmission()) - { - DeleteSelection(); - selection.Clear(); - MoveCaretToClosestEditableBuffer(); - } - else - { - return false; - } - } - else if (IsInActivePrompt(TextView.Caret.Position.BufferPosition)) - { - MoveCaretToClosestEditableBuffer(); - } - - // handle "RETURN" command that is not handled by either editor or service - var langCaret = GetPositionInLanguageBuffer(TextView.Caret.Position.BufferPosition); - - if (langCaret != null) - { - int caretPosition = langCaret.Value.Position; - - // note that caret might be located in virtual space behind the current buffer end: - if (trySubmit && caretPosition >= CurrentLanguageBuffer.CurrentSnapshot.Length && CanExecuteActiveCode()) - { - var dummy = SubmitAsync(); - } - else - { - // insert new line (triggers secondary prompt injection in buffer changed event): - CurrentLanguageBuffer.Insert(caretPosition, _lineBreakString); - IndentCurrentLine(TextView.Caret.Position.BufferPosition); - ScrollToCaret(); - } - return true; - } - - return false; - } - - private bool CanExecuteActiveCode() - { - Debug.Assert(CurrentLanguageBuffer != null); - - var input = GetActiveCode(); - if (string.IsNullOrWhiteSpace(input)) - { - // Always allow "execution" of a blank line. - // This will just close the current prompt and start a new one - return true; - } - - // Ignore any whitespace past the insertion point when determining - // whether or not we're at the end of the input - var pt = GetActiveCodeInsertionPosition(); - var isEnd = (pt == input.Length) || (pt >= 0 && input.Substring(pt).Trim().Length == 0); - if (!isEnd) - { - return false; - } - - // If this throws, VS shows a dialog. - return Evaluator.CanExecuteCode(input); - } - - /// - /// Returns the insertion point relative to the current language buffer. - /// - private int GetActiveCodeInsertionPosition() - { - Debug.Assert(CurrentLanguageBuffer != null); - - var langPoint = TextView.BufferGraph.MapDownToBuffer( - new SnapshotPoint( - _projectionBuffer.CurrentSnapshot, - TextView.Caret.Position.BufferPosition.Position), - PointTrackingMode.Positive, - CurrentLanguageBuffer, - PositionAffinity.Predecessor); - - if (langPoint != null) - { - return langPoint.Value; - } - - return CurrentLanguageBuffer.CurrentSnapshot.Length; - } - - private object CreateStandardInputPrompt() - { - return string.Empty; - } - - private object CreatePrimaryPrompt() - { - return Evaluator.GetPrompt(); - } - - private object CreateSecondaryPrompt() - { - // TODO (crwilcox) format prompt used to get a blank here but now gets "> " from get prompt. - return Evaluator.GetPrompt(); - } - - private ReplSpanKind GetSpanKind(SnapshotSpan span) - { - var textBuffer = span.Snapshot.TextBuffer; - if (textBuffer == OutputBuffer) - { - return ReplSpanKind.Output; - } - if (textBuffer == StandardInputBuffer) - { - return ReplSpanKind.StandardInput; - } - if (textBuffer.ContentType == _inertType) - { - return (span.Length == _lineBreakString.Length) && string.Equals(span.GetText(), _lineBreakString) ? - ReplSpanKind.LineBreak : - ReplSpanKind.Prompt; - } - return ReplSpanKind.Input; - } - - private int IndexOfLastSpan(ReadOnlyCollection sourceSpans, ReplSpanKind spanKind) - { - for (var i = sourceSpans.Count - 1; i >= 0; i--) - { - if (GetSpanKind(sourceSpans[i]) == spanKind) - { - return i; - } - } - - return -1; - } - - #region Output - - /// Implements . - public Span Write(string text) - { - int result = _buffer.Write(text); - return new Span(result, (text != null ? text.Length : 0)); - } - - /// Implements . - public Span WriteLine(string text) - { - int result = _buffer.Write(text); - _buffer.Write(_lineBreakString); - return new Span(result, (text != null ? text.Length : 0) + _lineBreakString.Length); - } - - /// Implements . - public Span WriteError(string text) - { - int result = _buffer.Write(text); - var res = new Span(result, (text != null ? text.Length : 0)); - ErrorOutputWriter.Spans.Add(res); - return res; - } - - /// Implements . - public Span WriteErrorLine(string text) - { - int result = _buffer.Write(text); - _buffer.Write(_lineBreakString); - var res = new Span(result, (text != null ? text.Length : 0) + _lineBreakString.Length); - ErrorOutputWriter.Spans.Add(res); - return res; - } - - /// Implements . - public void Write(UIElement element) - { - if (element == null) - { - return; - } - - _buffer.Flush(); - InlineAdornmentProvider.AddInlineAdornment(TextView, element, OnAdornmentLoaded); - _adornmentToMinimize = true; - WriteLine(string.Empty); - WriteLine(string.Empty); - } - - private void OnAdornmentLoaded(object source, EventArgs e) - { - // Make sure the caret line is rendered - DoEvents(); - TextView.Caret.EnsureVisible(); - } - - #endregion - - void IDisposable.Dispose() - { - if (_buffer != null) - { - _buffer.Dispose(); - } - } - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.cs b/src/InteractiveWindow/Editor/InteractiveWindow.cs deleted file mode 100644 index 84e4e179b8b8f..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.cs +++ /dev/null @@ -1,596 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -// Dumps commands in QueryStatus and Exec. -// #define DUMP_COMMANDS - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Threading; -using Microsoft.VisualStudio.Language.Intellisense; -using Microsoft.VisualStudio.Language.Intellisense.Utilities; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Formatting; -using Microsoft.VisualStudio.Text.Operations; -using Microsoft.VisualStudio.Text.Projection; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - // TODO: We should condense committed language buffers into a single language buffer and save the - // classifications from the previous language buffer if the perf of having individual buffers - // starts having problems w/ a large number of inputs. - - /// - /// Provides implementation of a Repl Window built on top of the VS editor using projection buffers. - /// - internal partial class InteractiveWindow : IInteractiveWindow2, IInteractiveWindowOperations2 - { - // The following two field definitions have to stay in sync with VS editor implementation - - /// - /// A data format used to tag the contents of the clipboard so that it's clear - /// the data has been put in the clipboard by our editor - /// - internal const string ClipboardLineBasedCutCopyTag = "VisualStudioEditorOperationsLineCutCopyClipboardTag"; - - /// - /// A data format used to tag the contents of the clipboard as a box selection. - /// This is the same string that was used in VS9 and previous versions. - /// - internal const string BoxSelectionCutCopyTag = "MSDEVColumnSelect"; - - public event EventHandler SubmissionBufferAdded; - - PropertyCollection IPropertyOwner.Properties { get; } = new PropertyCollection(); - - private readonly SemaphoreSlim _inputReaderSemaphore = new SemaphoreSlim(initialCount: 1, maxCount: 1); - - /// - /// WARNING: Members of this object should only be accessed from the UI thread. - /// - private readonly UIThreadOnly _uiOnly; - - // Setter for InteractiveWindowClipboard is a test hook. - internal InteractiveWindowClipboard InteractiveWindowClipboard { get; set; } = new SystemClipboard(); - - #region Initialization - - public InteractiveWindow( - IInteractiveWindowEditorFactoryService host, - IContentTypeRegistryService contentTypeRegistry, - ITextBufferFactoryService bufferFactory, - IProjectionBufferFactoryService projectionBufferFactory, - IEditorOperationsFactoryService editorOperationsFactory, - ITextBufferUndoManagerProvider textBufferUndoManagerProvider, - ITextEditorFactoryService editorFactory, - IRtfBuilderService rtfBuilderService, - IIntellisenseSessionStackMapService intellisenseSessionStackMap, - ISmartIndentationService smartIndenterService, - IInteractiveEvaluator evaluator, - IWaitIndicator waitIndicator) - { - if (evaluator == null) - { - throw new ArgumentNullException(nameof(evaluator)); - } - - _uiOnly = new UIThreadOnly( - this, - host, - contentTypeRegistry, - bufferFactory, - projectionBufferFactory, - editorOperationsFactory, - textBufferUndoManagerProvider, - editorFactory, - rtfBuilderService, - intellisenseSessionStackMap, - smartIndenterService, - evaluator, - waitIndicator); - - evaluator.CurrentWindow = this; - - RequiresUIThread(); - } - - async Task IInteractiveWindow.InitializeAsync() - { - try - { - RequiresUIThread(); - var uiOnly = _uiOnly; // Verified above. - - if (uiOnly.State != State.Starting) - { - throw new InvalidOperationException(InteractiveWindowResources.AlreadyInitialized); - } - - uiOnly.State = State.Initializing; - - // Anything that reads options should wait until after this call so the evaluator can set the options first - ExecutionResult result = await uiOnly.Evaluator.InitializeAsync().ConfigureAwait(continueOnCapturedContext: true); - Debug.Assert(OnUIThread()); // ConfigureAwait should bring us back to the UI thread. - - if (result.IsSuccessful) - { - uiOnly.PrepareForInput(); - } - - return result; - } - catch (Exception e) when (ReportAndPropagateException(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - private bool ReportAndPropagateException(Exception e) - { - FatalError.ReportWithoutCrashUnlessCanceled(e); // Drop return value. - - ((IInteractiveWindow)this).WriteErrorLine(InteractiveWindowResources.InternalError); - - return false; // Never consider the exception handled. - } - - #endregion - - void IInteractiveWindow.Close() - { - UIThread(uiOnly => uiOnly.Close()); - } - - #region Misc Helpers - - /// - /// The caller is responsible for using the buffer in a thread-safe manner. - /// - public ITextBuffer CurrentLanguageBuffer => _uiOnly.CurrentLanguageBuffer; - - void IDisposable.Dispose() - { - UIThread(uiOnly => ((IDisposable)uiOnly).Dispose()); - } - - public static InteractiveWindow FromBuffer(ITextBuffer buffer) - { - object result; - buffer.Properties.TryGetProperty(typeof(InteractiveWindow), out result); - return result as InteractiveWindow; - } - - #endregion - - #region IInteractiveWindow - - public event Action ReadyForInput; - - /// - /// The caller is responsible for using the text view in a thread-safe manner. - /// - IWpfTextView IInteractiveWindow.TextView => _uiOnly.TextView; - - /// - /// The caller is responsible for using the buffer in a thread-safe manner. - /// - ITextBuffer IInteractiveWindow.OutputBuffer => _uiOnly.OutputBuffer; - - /// - /// The caller is responsible for using the writer in a thread-safe manner. - /// - TextWriter IInteractiveWindow.OutputWriter => _uiOnly.OutputWriter; - - /// - /// The caller is responsible for using the writer in a thread-safe manner. - /// - TextWriter IInteractiveWindow.ErrorOutputWriter => _uiOnly.ErrorOutputWriter; - - /// - /// The caller is responsible for using the evaluator in a thread-safe manner. - /// - IInteractiveEvaluator IInteractiveWindow.Evaluator => _uiOnly.Evaluator; - - /// - /// Normally, an async method would have an NFW exception filter. This - /// one doesn't because it just calls other async methods that already - /// have filters. - /// - async Task IInteractiveWindow.SubmitAsync(IEnumerable inputs) - { - var completion = new TaskCompletionSource(); - var submissions = inputs.ToArray(); - var numSubmissions = submissions.Length; - PendingSubmission[] pendingSubmissions = new PendingSubmission[numSubmissions]; - if (numSubmissions == 0) - { - completion.SetResult(null); - } - else - { - for (int i = 0; i < numSubmissions; i++) - { - pendingSubmissions[i] = new PendingSubmission(submissions[i], i == numSubmissions - 1 ? completion : null); - } - } - - UIThread(uiOnly => uiOnly.Submit(pendingSubmissions)); - - // This indicates that the last submission has completed. - await completion.Task.ConfigureAwait(false); - - // These should all have finished already, but we'll await them so that their - // statuses are folded into the task we return. - await Task.WhenAll(pendingSubmissions.Select(p => p.Task)).ConfigureAwait(false); - } - - void IInteractiveWindow.AddInput(string command) - { - UIThread(uiOnly => uiOnly.AddInput(command)); - } - - void IInteractiveWindow2.AddToHistory(string input) - { - UIThread(uiOnly => uiOnly.AddToHistory(input)); - } - - void IInteractiveWindow.FlushOutput() - { - UIThread(uiOnly => uiOnly.FlushOutput()); - } - - void IInteractiveWindow.InsertCode(string text) - { - UIThread(uiOnly => uiOnly.InsertCode(text)); - } - - #endregion - - #region Commands - - Task IInteractiveWindowOperations.ResetAsync(bool initialize) - { - return UIThread(uiOnly => uiOnly.ResetAsync(initialize)); - } - - void IInteractiveWindowOperations.ClearHistory() - { - UIThread(uiOnly => uiOnly.ClearHistory()); - } - - void IInteractiveWindowOperations.ClearView() - { - UIThread(uiOnly => uiOnly.ClearView()); - } - - /// - /// Pastes from the clipboard into the text view - /// - bool IInteractiveWindowOperations.Paste() - { - return UIThread(uiOnly => uiOnly.Paste()); - } - - void IInteractiveWindowOperations.ExecuteInput() - { - UIThread(uiOnly => uiOnly.ExecuteInputAsync()); - } - - /// - /// Test hook. - /// - internal Task ExecuteInputAsync() - { - return UIThread(uiOnly => uiOnly.ExecuteInputAsync()); - } - - /// - /// Appends text to the output buffer and updates projection buffer to include it. - /// WARNING: this has to be the only method that writes to the output buffer so that - /// the output buffering counters are kept in sync. - /// - internal void AppendOutput(IEnumerable output) - { - RequiresUIThread(); - _uiOnly.AppendOutput(output); // Verified above. - } - - /// - /// Clears the current input - /// - void IInteractiveWindowOperations.Cancel() - { - UIThread(uiOnly => uiOnly.Cancel()); - } - - void IInteractiveWindowOperations.HistoryPrevious(string search) - { - UIThread(uiOnly => uiOnly.HistoryPrevious(search)); - } - - void IInteractiveWindowOperations.HistoryNext(string search) - { - UIThread(uiOnly => uiOnly.HistoryNext(search)); - } - - void IInteractiveWindowOperations.HistorySearchNext() - { - UIThread(uiOnly => uiOnly.HistorySearchNext()); - } - - void IInteractiveWindowOperations.HistorySearchPrevious() - { - UIThread(uiOnly => uiOnly.HistorySearchPrevious()); - } - - /// - /// Moves to the beginning of the line. - /// - void IInteractiveWindowOperations.Home(bool extendSelection) - { - UIThread(uiOnly => uiOnly.Home(extendSelection)); - } - - /// - /// Moves to the end of the line. - /// - void IInteractiveWindowOperations.End(bool extendSelection) - { - UIThread(uiOnly => uiOnly.End(extendSelection)); - } - - void IInteractiveWindowOperations.SelectAll() - { - UIThread(uiOnly => uiOnly.SelectAll()); - } - - #endregion - - #region Keyboard Commands - - /// Only consistent on the UI thread. - bool IInteractiveWindow.IsRunning => _uiOnly.State != State.WaitingForInput; - - /// Only consistent on the UI thread. - bool IInteractiveWindow.IsResetting => _uiOnly.State == State.Resetting || _uiOnly.State == State.ResettingAndReadingStandardInput; - - /// Only consistent on the UI thread. - bool IInteractiveWindow.IsInitializing => _uiOnly.State == State.Starting || _uiOnly.State == State.Initializing; - - IInteractiveWindowOperations IInteractiveWindow.Operations => this; - - bool IInteractiveWindowOperations.Delete() - { - return UIThread(uiOnly => uiOnly.Delete()); - } - - void IInteractiveWindowOperations.Cut() - { - UIThread(uiOnly => uiOnly.Cut()); - } - - void IInteractiveWindowOperations2.Copy() - { - UIThread(uiOnly => uiOnly.Copy()); - } - - void IInteractiveWindowOperations2.CopyCode() - { - UIThread(uiOnly => uiOnly.CopyCode()); - } - - bool IInteractiveWindowOperations.Backspace() - { - return UIThread(uiOnly => uiOnly.Backspace()); - } - - bool IInteractiveWindowOperations.TrySubmitStandardInput() - { - return UIThread(uiOnly => uiOnly.TrySubmitStandardInput()); - } - - bool IInteractiveWindowOperations.BreakLine() - { - return UIThread(uiOnly => uiOnly.BreakLine()); - } - - bool IInteractiveWindowOperations.Return() - { - return UIThread(uiOnly => uiOnly.Return()); - } - - void IInteractiveWindowOperations2.DeleteLine() - { - UIThread(uiOnly => uiOnly.DeleteLine()); - } - - void IInteractiveWindowOperations2.CutLine() - { - UIThread(uiOnly => uiOnly.CutLine()); - } - - void IInteractiveWindowOperations2.TypeChar(char typedChar) - { - UIThread(uiOnly => uiOnly.TypeChar(typedChar)); - } - - #endregion - - #region Command Debugging - -#if DUMP_COMMANDS - private static void DumpCmd(string prefix, int result, ref Guid pguidCmdGroup, uint cmd, uint cmdf) - { - string cmdName; - if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) - { - cmdName = ((VSConstants.VSStd97CmdID)cmd).ToString(); - } - else if (pguidCmdGroup == VSConstants.VSStd2K) - { - cmdName = ((VSConstants.VSStd2KCmdID)cmd).ToString(); - } - else if (pguidCmdGroup == VSConstants.VsStd2010) - { - cmdName = ((VSConstants.VSStd2010CmdID)cmd).ToString(); - } - else if (pguidCmdGroup == GuidList.guidReplWindowCmdSet) - { - cmdName = ((ReplCommandId)cmd).ToString(); - } - else - { - return; - } - - Debug.WriteLine("{3}({0}) -> {1} {2}", cmdName, Enum.Format(typeof(OLECMDF), (OLECMDF)cmdf, "F"), result, prefix); - } -#endif - - #endregion - - #region Active Code and Standard Input - - TextReader IInteractiveWindow.ReadStandardInput() - { - // shouldn't be called on the UI thread because we'll hang - RequiresNonUIThread(); - return ReadStandardInputAsync().GetAwaiter().GetResult(); - } - - private async Task ReadStandardInputAsync() - { - try - { - // True because this is a public API and we want to use the same - // thread as the caller (esp for blocking). - await _inputReaderSemaphore.WaitAsync().ConfigureAwait(true); // Only one thread can read from standard input at a time. - try - { - return await UIThread(uiOnly => uiOnly.ReadStandardInputAsync()).ConfigureAwait(true); - } - finally - { - _inputReaderSemaphore.Release(); - } - } - catch (Exception e) when (ReportAndPropagateException(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - #endregion - - #region Output - - Span IInteractiveWindow.Write(string text) - { - return UIThread(uiOnly => uiOnly.Write(text)); - } - - Span IInteractiveWindow.WriteLine(string text) - { - return UIThread(uiOnly => uiOnly.WriteLine(text)); - } - - Span IInteractiveWindow.WriteError(string text) - { - return UIThread(uiOnly => uiOnly.WriteError(text)); - } - - Span IInteractiveWindow.WriteErrorLine(string text) - { - return UIThread(uiOnly => uiOnly.WriteErrorLine(text)); - } - - void IInteractiveWindow.Write(UIElement element) - { - UIThread(uiOnly => uiOnly.Write(element)); - } - - #endregion - - #region UI Dispatcher Helpers - - private Dispatcher Dispatcher => ((FrameworkElement)_uiOnly.TextView).Dispatcher; // Always safe to access the dispatcher. - - internal bool OnUIThread() - { - return Dispatcher.CheckAccess(); - } - - private T UIThread(Func func) - { - if (!OnUIThread()) - { - return (T)Dispatcher.Invoke(func, _uiOnly); // Safe because of dispatch. - } - - return func(_uiOnly); // Safe because of check. - } - - private void UIThread(Action action) - { - if (!OnUIThread()) - { - Dispatcher.Invoke(action, _uiOnly); // Safe because of dispatch. - return; - } - - action(_uiOnly); // Safe because of check. - } - - private void RequiresUIThread() - { - if (!OnUIThread()) - { - throw new InvalidOperationException(InteractiveWindowResources.RequireUIThread); - } - } - - private void RequiresNonUIThread() - { - if (OnUIThread()) - { - throw new InvalidOperationException(InteractiveWindowResources.RequireNonUIThread); - } - } - - private static void DoEvents() - { - var frame = new DispatcherFrame(); - Dispatcher.CurrentDispatcher.BeginInvoke( - DispatcherPriority.Background, - new Action(f => f.Continue = false), - frame); - - Dispatcher.PushFrame(frame); - } - - #endregion - - #region Testing - - internal event Action StateChanged; - - internal void Undo_TestOnly(int count) - { - UIThread(uiOnly => uiOnly.UndoHistory?.Undo(count)); - } - - internal void Redo_TestOnly(int count) - { - UIThread(uiOnly => uiOnly.UndoHistory?.Redo(count)); - } - - #endregion - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindow.csproj b/src/InteractiveWindow/Editor/InteractiveWindow.csproj deleted file mode 100644 index 82365cbc9241d..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindow.csproj +++ /dev/null @@ -1,112 +0,0 @@ - - - - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - Library - Microsoft.VisualStudio.InteractiveWindow - Microsoft.VisualStudio.InteractiveWindow - false - v4.6 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - InteractiveWindowResources.resx - - - - - - - - - - - - - - - - - - - - - - - - ResXFileCodeGenerator - InteractiveWindowResources.Designer.cs - Designer - - - - - - - - - diff --git a/src/InteractiveWindow/Editor/InteractiveWindowClipboard.cs b/src/InteractiveWindow/Editor/InteractiveWindowClipboard.cs deleted file mode 100644 index 3baedda3c9323..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindowClipboard.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Windows; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal abstract class InteractiveWindowClipboard - { - internal abstract bool ContainsData(string format); - - internal abstract object GetData(string format); - - internal abstract bool ContainsText(); - - internal abstract string GetText(); - - internal abstract void SetDataObject(object data, bool copy); - - internal abstract IDataObject GetDataObject(); - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindowExtensions.cs b/src/InteractiveWindow/Editor/InteractiveWindowExtensions.cs deleted file mode 100644 index 29ffbc2f60e6a..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindowExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - public static class InteractiveWindowExtensions - { - /// - /// Gets the interactive window associated with the text buffer if the text - /// buffer is being hosted in the interactive window. - /// - /// Returns null if the text buffer is not hosted in the interactive window. - /// - public static IInteractiveWindow GetInteractiveWindow(this ITextBuffer buffer) - { - return InteractiveWindow.FromBuffer(buffer); - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindowOptions.cs b/src/InteractiveWindow/Editor/InteractiveWindowOptions.cs deleted file mode 100644 index b436c914fdc32..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindowOptions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Text.Editor; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - public static class InteractiveWindowOptions - { - private static readonly EditorOptionKey s_smartUpDown = new EditorOptionKey(SmartUpDownOption.OptionName); - - /// - /// Indicates that the window should be using smart up/down behavior. When enabled pressing - /// the up or down arrow key will navigate history if the caret is at the end of the current - /// input. When disabled the up/down arrow keys will always navigate the buffer. - /// - public static EditorOptionKey SmartUpDown - { - get - { - return s_smartUpDown; - } - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindowProvider.cs b/src/InteractiveWindow/Editor/InteractiveWindowProvider.cs deleted file mode 100644 index 4d200d46c67f3..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindowProvider.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Language.Intellisense; -using Microsoft.VisualStudio.Language.Intellisense.Utilities; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Formatting; -using Microsoft.VisualStudio.Text.Operations; -using Microsoft.VisualStudio.Text.Projection; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - [Export(typeof(IInteractiveWindowFactoryService))] - internal class InteractiveWindowProvider : IInteractiveWindowFactoryService - { - private readonly IContentTypeRegistryService _contentTypeRegistry; - private readonly ITextBufferFactoryService _bufferFactory; - private readonly IProjectionBufferFactoryService _projectionBufferFactory; - private readonly IEditorOperationsFactoryService _editorOperationsFactory; - private readonly ITextBufferUndoManagerProvider _textBufferUndoManagerProvider; - private readonly ITextEditorFactoryService _editorFactory; - private readonly IRtfBuilderService _rtfBuilderService; - private readonly IIntellisenseSessionStackMapService _intellisenseSessionStackMap; - private readonly ISmartIndentationService _smartIndenterService; - private readonly IInteractiveWindowEditorFactoryService _windowFactoryService; - private readonly IWaitIndicator _waitIndicator; - - [ImportingConstructor] - public InteractiveWindowProvider( - IContentTypeRegistryService contentTypeRegistry, - ITextBufferFactoryService bufferFactory, - IProjectionBufferFactoryService projectionBufferFactory, - IEditorOperationsFactoryService editorOperationsFactory, - ITextBufferUndoManagerProvider textBufferUndoManagerProvider, - ITextEditorFactoryService editorFactory, - IRtfBuilderService rtfBuilderService, - IIntellisenseSessionStackMapService intellisenseSessionStackMap, - ISmartIndentationService smartIndenterService, - IInteractiveWindowEditorFactoryService windowFactoryService, - IWaitIndicator waitIndicator) - { - _contentTypeRegistry = contentTypeRegistry; - _bufferFactory = bufferFactory; - _projectionBufferFactory = projectionBufferFactory; - _editorOperationsFactory = editorOperationsFactory; - _textBufferUndoManagerProvider = textBufferUndoManagerProvider; - _editorFactory = editorFactory; - _rtfBuilderService = rtfBuilderService; - _intellisenseSessionStackMap = intellisenseSessionStackMap; - _smartIndenterService = smartIndenterService; - _windowFactoryService = windowFactoryService; - _waitIndicator = waitIndicator; - } - - public IInteractiveWindow CreateWindow(IInteractiveEvaluator evaluator) - { - if (evaluator == null) - { - throw new ArgumentNullException(nameof(evaluator)); - } - - return new InteractiveWindow( - _windowFactoryService, - _contentTypeRegistry, - _bufferFactory, - _projectionBufferFactory, - _editorOperationsFactory, - _textBufferUndoManagerProvider, - _editorFactory, - _rtfBuilderService, - _intellisenseSessionStackMap, - _smartIndenterService, - evaluator, - _waitIndicator); - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindowResources.Designer.cs b/src/InteractiveWindow/Editor/InteractiveWindowResources.Designer.cs deleted file mode 100644 index d264cb4b7a841..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindowResources.Designer.cs +++ /dev/null @@ -1,495 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.VisualStudio.InteractiveWindow { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class InteractiveWindowResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal InteractiveWindowResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.InteractiveWindow.InteractiveWindowResources", typeof(InteractiveWindowResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to The interactive window has already been initialized.. - /// - internal static string AlreadyInitialized { - get { - return ResourceManager.GetString("AlreadyInitialized", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace the current submission with a subsequent submission (after having previously navigated backwards).. - /// - internal static string AltDownArrowHelp { - get { - return ResourceManager.GetString("AltDownArrowHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace the current submission with a previous submission.. - /// - internal static string AltUpArrowHelp { - get { - return ResourceManager.GetString("AltUpArrowHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Delete Character To Left. - /// - internal static string Backspace { - get { - return ResourceManager.GetString("Backspace", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Insert New Line. - /// - internal static string BreakLine { - get { - return ResourceManager.GetString("BreakLine", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Clears the contents of the editor window, leaving history and execution context intact.. - /// - internal static string ClearScreenCommandDescription { - get { - return ResourceManager.GetString("ClearScreenCommandDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Command '{0}' failed: {1}. - /// - internal static string CommandFailed { - get { - return ResourceManager.GetString("CommandFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to [command-name]. - /// - internal static string CommandNamePlaceholder { - get { - return ResourceManager.GetString("CommandNamePlaceholder", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Script directives:. - /// - internal static string CSVBScriptDirectives { - get { - return ResourceManager.GetString("CSVBScriptDirectives", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to First press, select the submission containing the cursor. Second press, select all text in the window.. - /// - internal static string CtrlAHelp { - get { - return ResourceManager.GetString("CtrlAHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards).. - /// - internal static string CtrlAltDownArrowHelp { - get { - return ResourceManager.GetString("CtrlAltDownArrowHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Replace the current submission with a previous submission beginning with the same text.. - /// - internal static string CtrlAltUpArrowHelp { - get { - return ResourceManager.GetString("CtrlAltUpArrowHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Paste and execute the selection before any pending input in the interactive buffer.. - /// - internal static string CtrlECtrlEnterHelp { - get { - return ResourceManager.GetString("CtrlECtrlEnterHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Within the current submission, evaluate the current submission.. - /// - internal static string CtrlEnterHelp1 { - get { - return ResourceManager.GetString("CtrlEnterHelp1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Within a previous submission, append the previous submission to the current submission.. - /// - internal static string CtrlEnterHelp2 { - get { - return ResourceManager.GetString("CtrlEnterHelp2", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Paste the selection at the end of interactive buffer, leave caret at the end of input.. - /// - internal static string CtrlKCtrlEnterHelp { - get { - return ResourceManager.GetString("CtrlKCtrlEnterHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cut Selection. - /// - internal static string Cut { - get { - return ResourceManager.GetString("Cut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cut Line. - /// - internal static string CutLine { - get { - return ResourceManager.GetString("CutLine", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Delete Text. - /// - internal static string Delete { - get { - return ResourceManager.GetString("Delete", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Delete Line. - /// - internal static string DeleteLine { - get { - return ResourceManager.GetString("DeleteLine", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to At the end of the current submission, replace the current submission with a subsequent submission (after having previously navigated backwards).. - /// - internal static string DownArrowHelp1 { - get { - return ResourceManager.GetString("DownArrowHelp1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Elsewhere, move the cursor down one line.. - /// - internal static string DownArrowHelp2 { - get { - return ResourceManager.GetString("DownArrowHelp2", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A command with the name '{0}' has already been registered.. - /// - internal static string DuplicateCommand { - get { - return ResourceManager.GetString("DuplicateCommand", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to If the current submission appears to be complete, evaluate it. Otherwise, insert a new line.. - /// - internal static string EnterHelp { - get { - return ResourceManager.GetString("EnterHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Clear the current submission.. - /// - internal static string EscapeHelp { - get { - return ResourceManager.GetString("EscapeHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Display help on specified command, or all available commands and key bindings if none specified.. - /// - internal static string HelpCommandDescription { - get { - return ResourceManager.GetString("HelpCommandDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to An internal error has occurred in the Interactive window. Please restart Visual Studio.. - /// - internal static string InternalError { - get { - return ResourceManager.GetString("InternalError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The interactive window is resettings.. - /// - internal static string IsResettings { - get { - return ResourceManager.GetString("IsResettings", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Keyboard shortcuts:. - /// - internal static string KeyboardShortcuts { - get { - return ResourceManager.GetString("KeyboardShortcuts", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Load specified script file and execute it, e.g. #load "myScript.csx".. - /// - internal static string LoadHelp { - get { - return ResourceManager.GetString("LoadHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The command of type '{0}' has no command names.. - /// - internal static string MissingCommandName { - get { - return ResourceManager.GetString("MissingCommandName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The interactive window has not yet been initialized.. - /// - internal static string NotInitialized { - get { - return ResourceManager.GetString("NotInitialized", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Parameters:. - /// - internal static string Parameters { - get { - return ResourceManager.GetString("Parameters", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Paste. - /// - internal static string Paste { - get { - return ResourceManager.GetString("Paste", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".. - /// - internal static string RefHelp { - get { - return ResourceManager.GetString("RefHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to REPL commands:. - /// - internal static string ReplCommands { - get { - return ResourceManager.GetString("ReplCommands", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to This method may not be called on the UI thread (to avoid hangs).. - /// - internal static string RequireNonUIThread { - get { - return ResourceManager.GetString("RequireNonUIThread", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to This method may only be called on the UI thread.. - /// - internal static string RequireUIThread { - get { - return ResourceManager.GetString("RequireUIThread", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Reset the execution environment to the initial state, keep history.. - /// - internal static string ResetCommandDescription { - get { - return ResourceManager.GetString("ResetCommandDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Reset to a clean environment (only mscorlib referenced), do not run initialization script.. - /// - internal static string ResetCommandParametersDescription { - get { - return ResourceManager.GetString("ResetCommandParametersDescription", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Insert a new line.. - /// - internal static string ShiftEnterHelp { - get { - return ResourceManager.GetString("ShiftEnterHelp", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Insert Text. - /// - internal static string TypeChar { - get { - return ResourceManager.GetString("TypeChar", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unknown command '{0}'. - /// - internal static string UnknownCommand { - get { - return ResourceManager.GetString("UnknownCommand", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to At the end of the current submission, replace the current submission with a previous submission.. - /// - internal static string UpArrowHelp1 { - get { - return ResourceManager.GetString("UpArrowHelp1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Elsewhere, move the cursor up one line.. - /// - internal static string UpArrowHelp2 { - get { - return ResourceManager.GetString("UpArrowHelp2", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Usage:. - /// - internal static string Usage { - get { - return ResourceManager.GetString("Usage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generating Rich Text Format representation from selection.. - /// - internal static string WaitMessage { - get { - return ResourceManager.GetString("WaitMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Copy. - /// - internal static string WaitTitle { - get { - return ResourceManager.GetString("WaitTitle", resourceCulture); - } - } - } -} diff --git a/src/InteractiveWindow/Editor/InteractiveWindowResources.resx b/src/InteractiveWindow/Editor/InteractiveWindowResources.resx deleted file mode 100644 index 230398edd49a3..0000000000000 --- a/src/InteractiveWindow/Editor/InteractiveWindowResources.resx +++ /dev/null @@ -1,264 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - The interactive window has already been initialized. - - - Replace the current submission with a subsequent submission (after having previously navigated backwards). - - - Replace the current submission with a previous submission. - - - Clears the contents of the editor window, leaving history and execution context intact. - - - Command '{0}' failed: {1} - - - [command-name] - - - First press, select the submission containing the cursor. Second press, select all text in the window. - - - Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards). - - - Replace the current submission with a previous submission beginning with the same text. - - - Paste and execute the selection before any pending input in the interactive buffer. - - - Within the current submission, evaluate the current submission. - - - Within a previous submission, append the previous submission to the current submission. - - - Paste the selection at the end of interactive buffer, leave caret at the end of input. - - - At the end of the current submission, replace the current submission with a subsequent submission (after having previously navigated backwards). - - - Elsewhere, move the cursor down one line. - - - A command with the name '{0}' has already been registered. - - - If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. - - - Clear the current submission. - - - Display help on specified command, or all available commands and key bindings if none specified. - - - An internal error has occurred in the Interactive window. Please restart Visual Studio. - - - Keyboard shortcuts: - - - The command of type '{0}' has no command names. - - - The interactive window has not yet been initialized. - - - The interactive window is resettings. - - - Parameters: - - - REPL commands: - - - This method may not be called on the UI thread (to avoid hangs). - - - This method may only be called on the UI thread. - - - Reset the execution environment to the initial state, keep history. - - - Reset to a clean environment (only mscorlib referenced), do not run initialization script. - - - Insert a new line. - - - Unknown command '{0}' - - - At the end of the current submission, replace the current submission with a previous submission. - - - Elsewhere, move the cursor up one line. - - - Usage: - - - Copy - - - Generating Rich Text Format representation from selection. - - - Delete Character To Left - - - Insert New Line - - - Paste - - - Cut Selection - - - Delete Text - - - Cut Line - - - Delete Line - - - Insert Text - - - Script directives: - - - Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". - - - Load specified script file and execute it, e.g. #load "myScript.csx". - - \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/InternalUtilities/ExceptionUtilities.cs b/src/InteractiveWindow/Editor/InternalUtilities/ExceptionUtilities.cs deleted file mode 100644 index bb4504e7dedde..0000000000000 --- a/src/InteractiveWindow/Editor/InternalUtilities/ExceptionUtilities.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal static class ExceptionUtilities - { - internal static Exception UnexpectedValue(object o) - { - string output = string.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : ""); - Debug.Assert(false, output); - - // We do not throw from here because we don't want all Watson reports to be bucketed to this call. - return new InvalidOperationException(output); - } - - internal static Exception Unreachable - { - get { return new InvalidOperationException("This program location is thought to be unreachable."); } - } - } -} diff --git a/src/InteractiveWindow/Editor/InternalUtilities/FatalError.cs b/src/InteractiveWindow/Editor/InternalUtilities/FatalError.cs deleted file mode 100644 index c38ed3f592c77..0000000000000 --- a/src/InteractiveWindow/Editor/InternalUtilities/FatalError.cs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.ComponentModel; -using System.Diagnostics; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal static class FatalError - { - private static Action s_fatalHandler; - private static Action s_nonFatalHandler; - - private static Exception s_reportedException; - private static string s_reportedExceptionMessage; - - /// - /// Set by the host to a fail fast trigger, - /// if the host desires to crash the process on a fatal exception. - /// - public static Action Handler - { - get - { - return s_fatalHandler; - } - - set - { - if (s_fatalHandler != value) - { - Debug.Assert(s_fatalHandler == null, "Handler already set"); - s_fatalHandler = value; - } - } - } - - /// - /// Set by the host to a fail fast trigger, - /// if the host desires to NOT crash the process on a non fatal exception. - /// - public static Action NonFatalHandler - { - get - { - return s_nonFatalHandler; - } - - set - { - if (s_nonFatalHandler != value) - { - Debug.Assert(s_nonFatalHandler == null, "Handler already set"); - s_nonFatalHandler = value; - } - } - } - - // Same as setting the Handler property except that it avoids the assert. This is useful in - // test code which needs to verify the handler is called in specific cases and will continually - // overwrite this value. - public static void OverwriteHandler(Action value) - { - s_fatalHandler = value; - } - - /// - /// Use in an exception filter to report a fatal error. - /// Unless the exception is - /// it calls . The exception is passed through (the method returns false). - /// - /// False to avoid catching the exception. - [DebuggerHidden] - public static bool ReportUnlessCanceled(Exception exception) - { - if (exception is OperationCanceledException) - { - return false; - } - - return Report(exception); - } - - /// - /// Use in an exception filter to report a non fatal error. - /// Unless the exception is - /// it calls . The exception isn't passed through (the method returns true). - /// - /// True to catch the exception. - [DebuggerHidden] - public static bool ReportWithoutCrashUnlessCanceled(Exception exception) - { - if (exception is OperationCanceledException) - { - return false; - } - - return ReportWithoutCrash(exception); - } - - /// - /// Use in an exception filter to report a fatal error. - /// Unless the exception is - /// it calls . The exception is passed through (the method returns false). - /// - /// False to avoid catching the exception. - [DebuggerHidden] - public static bool ReportUnlessNotImplemented(Exception exception) - { - if (exception is NotImplementedException) - { - return false; - } - - return Report(exception); - } - - /// - /// Use in an exception filter to report a fatal error. - /// Calls and passes the exception through (the method returns false). - /// - /// False to avoid catching the exception. - [DebuggerHidden] - public static bool Report(Exception exception) - { - Report(exception, s_fatalHandler); - return false; - } - - /// - /// Use in an exception filter to report a non fatal error. - /// Calls and doesn't pass the exception through (the method returns true). - /// - /// True to catch the exception. - [DebuggerHidden] - public static bool ReportWithoutCrash(Exception exception) - { - Report(exception, s_nonFatalHandler); - return true; - } - - private static void Report(Exception exception, Action handler) - { - // hold onto last exception to make investigation easier - s_reportedException = exception; - s_reportedExceptionMessage = exception.ToString(); - - handler?.Invoke(exception); - } - } -} diff --git a/src/InteractiveWindow/Editor/Output/InlineAdornmentProvider.cs b/src/InteractiveWindow/Editor/Output/InlineAdornmentProvider.cs deleted file mode 100644 index 1eccbf6014883..0000000000000 --- a/src/InteractiveWindow/Editor/Output/InlineAdornmentProvider.cs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.Windows; -using System.Windows.Threading; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Tagging; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - [Export(typeof(IViewTaggerProvider))] - [TagType(typeof(IntraTextAdornmentTag))] - [ContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName)] - internal sealed class InlineAdornmentProvider : IViewTaggerProvider - { - public ITagger CreateTagger(ITextView textView, ITextBuffer buffer) where T : ITag - { - if (buffer == null || textView == null || typeof(T) != typeof(IntraTextAdornmentTag)) - { - return null; - } - - return (ITagger)textView.Properties.GetOrCreateSingletonProperty( - typeof(InlineReplAdornmentManager), - () => new InlineReplAdornmentManager(textView)); - } - - private class InlineReplAdornmentManager : ITagger - { - private readonly ITextView _textView; - private readonly List> _tags; - private readonly Dispatcher _dispatcher; - - internal InlineReplAdornmentManager(ITextView textView) - { - _textView = textView; - _tags = new List>(); - _dispatcher = Dispatcher.CurrentDispatcher; - } - - public IEnumerable> GetTags(NormalizedSnapshotSpanCollection spans) - { - var result = new List>(); - foreach (var t in _tags) - { - var span = new SnapshotSpan(_textView.TextSnapshot, t.Item1, 0); - t.Item2.UpdateSize(); - var tag = new IntraTextAdornmentTag(t.Item2, null); - result.Add(new TagSpan(span, tag)); - } - - return result; - } - - public void AddAdornment(ZoomableInlineAdornment uiElement) - { - if (Dispatcher.CurrentDispatcher != _dispatcher) - { - _dispatcher.BeginInvoke(new Action(() => AddAdornment(uiElement))); - return; - } - - var caretPos = _textView.Caret.Position.BufferPosition; - var caretLine = caretPos.GetContainingLine(); - _tags.Add(new Tuple(caretPos.Position, uiElement)); - - var handler = TagsChanged; - if (handler != null) - { - var span = new SnapshotSpan(_textView.TextSnapshot, caretLine.Start, caretLine.Length); - var args = new SnapshotSpanEventArgs(span); - handler(this, args); - } - } - - public IList> Adornments - { - get { return _tags; } - } - - public void RemoveAll() - { - _tags.Clear(); - } - - public event EventHandler TagsChanged; - } - - private static InlineReplAdornmentManager GetManager(ITextView view) - { - InlineReplAdornmentManager result; - if (!view.Properties.TryGetProperty(typeof(InlineReplAdornmentManager), out result)) - { - return null; - } - - return result; - } - - public static void AddInlineAdornment(ITextView view, UIElement uiElement, RoutedEventHandler onLoaded) - { - var manager = GetManager(view); - if (manager != null) - { - var adornment = new ZoomableInlineAdornment(uiElement, view); - - // Original Python code unhooked this event after load was complete - // I don't think this should be needed... we'll see. - adornment.Loaded += onLoaded; - manager.AddAdornment(adornment); - } - } - - public static void ZoomInlineAdornments(ITextView view, double zoomFactor) - { - var manager = GetManager(view); - if (manager != null) - { - foreach (var t in manager.Adornments) - { - t.Item2.Zoom(zoomFactor); - } - } - } - - public static void MinimizeLastInlineAdornment(ITextView view) - { - var manager = GetManager(view); - if (manager != null && manager.Adornments.Count > 0) - { - var adornment = manager.Adornments[manager.Adornments.Count - 1].Item2; - adornment.Zoom(adornment.MinimizedZoom); - } - } - - public static void RemoveAllAdornments(ITextView view) - { - var manager = GetManager(view); - if (manager != null) - { - manager.RemoveAll(); - } - } - } -} diff --git a/src/InteractiveWindow/Editor/Output/OutputBuffer.cs b/src/InteractiveWindow/Editor/Output/OutputBuffer.cs deleted file mode 100644 index 83d85cea73574..0000000000000 --- a/src/InteractiveWindow/Editor/Output/OutputBuffer.cs +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Windows.Threading; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// Serializes and buffers output so that we avoid frequent switching to UI thread to write to the editor buffer. - /// - internal sealed class OutputBuffer : IDisposable - { - private sealed class Entry - { - public readonly string Text; - public Entry Next; - - public Entry(string text) - { - Debug.Assert(!string.IsNullOrEmpty(text)); - Text = text; - } - } - - private static readonly Stopwatch s_stopwatch; - - private readonly InteractiveWindow _window; - private readonly DispatcherTimer _timer; - private readonly object _mutex; - - private Entry _firstEntry; - private Entry _lastEntry; - - private long _lastFlushTimeMilliseconds; - - // the number of characters written to the buffer that trigger an auto-flush - private int _flushThreshold; - - // the number of characters written to the buffer that haven't been flushed yet - private int _unflushedLength; - - // the number of characters written to the output (doesn't reset on flush) - private int _totalLength; - - private const int InitialFlushThreshold = 1024; - private const int AutoFlushMilliseconds = 100; - - static OutputBuffer() - { - s_stopwatch = new Stopwatch(); - s_stopwatch.Start(); - } - - public OutputBuffer(InteractiveWindow window) - { - Reset(); - - _mutex = new object(); - _window = window; - - _timer = new DispatcherTimer(); - _timer.Tick += (sender, args) => Flush(); - _timer.Interval = TimeSpan.FromMilliseconds(AutoFlushMilliseconds); - } - - internal void Reset() - { - _firstEntry = _lastEntry = null; - _totalLength = _unflushedLength = 0; - _flushThreshold = InitialFlushThreshold; - } - - /// - /// Appends text to the end of the buffer. - /// - /// Text to append. - /// Returns the position where this text is inserted relative to the buffer start. - public int Write(string text) - { - int result = _totalLength; - - if (string.IsNullOrEmpty(text)) - { - return result; - } - - bool needsFlush = false; - lock (_mutex) - { - AddEntry(text); - - needsFlush = _unflushedLength > _flushThreshold; - if (!needsFlush && !_timer.IsEnabled) - { - _timer.IsEnabled = true; - } - } - - if (needsFlush) - { - Flush(); - } - - return result; - } - - /// - /// Flushes the buffer, should always be called from the UI thread. - /// - public void Flush() - { - Entry firstEntryToFlush = null; - - lock (_mutex) - { - // if we're rapidly outputting grow the threshold - long curTime = s_stopwatch.ElapsedMilliseconds; - if (curTime - _lastFlushTimeMilliseconds < 1000) - { - if (_flushThreshold < 1024 * 1024) - { - _flushThreshold *= 2; - } - } - - _lastFlushTimeMilliseconds = s_stopwatch.ElapsedMilliseconds; - - if (_unflushedLength > 0) - { - // normalize line breaks - the editor isn't happy about projections that cut "\r\n" line break in half: - if (_lastEntry.Text[_lastEntry.Text.Length - 1] == '\r') - { - AddEntry("\n"); - } - - firstEntryToFlush = _firstEntry; - - _firstEntry = _lastEntry = null; - _unflushedLength = 0; - } - - _timer.IsEnabled = false; - } - - if (firstEntryToFlush != null) - { - _window.AppendOutput(GetEntries(firstEntryToFlush)); - } - } - - private void AddEntry(string text) - { - var entry = new Entry(text); - - if (_firstEntry == null) - { - _firstEntry = _lastEntry = entry; - } - else - { - _lastEntry.Next = entry; - _lastEntry = entry; - } - - _totalLength += text.Length; - _unflushedLength += text.Length; - } - - private IEnumerable GetEntries(Entry entry) - { - while (entry != null) - { - yield return entry.Text; - entry = entry.Next; - } - } - - public void Dispose() - { - _timer.IsEnabled = false; - } - } -} diff --git a/src/InteractiveWindow/Editor/Output/OutputClassifierProvider.cs b/src/InteractiveWindow/Editor/Output/OutputClassifierProvider.cs deleted file mode 100644 index fb252a1ae22a1..0000000000000 --- a/src/InteractiveWindow/Editor/Output/OutputClassifierProvider.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.Windows.Media; -using Microsoft.VisualStudio.Language.StandardClassification; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Classification; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - /// - /// Classifies error text in interactive window output. - /// - [Export(typeof(IClassifierProvider))] - [ContentType(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName)] - internal sealed class OutputClassifierProvider : IClassifierProvider - { - private static readonly object s_textBufferPropertyKey = new object(); - - [Import] - private IClassificationTypeRegistryService _classificationRegistry = null; - - public IClassifier GetClassifier(ITextBuffer textBuffer) - { - return new Classifier( - textBuffer, - _classificationRegistry.GetClassificationType(FormatDefinitions.ErrorOutput.Name)); - } - - internal static void AttachToBuffer(ITextBuffer buffer, SortedSpans spans) - { - buffer.Properties[s_textBufferPropertyKey] = spans; - } - - internal static void ClearSpans(ITextBuffer buffer) - { - SortedSpans errorSpans; - if (buffer.Properties.TryGetProperty(s_textBufferPropertyKey, out errorSpans)) - { - errorSpans.Clear(); - } - } - - private sealed class Classifier : IClassifier - { - private readonly ITextBuffer _buffer; - private readonly IClassificationType _errorOutputType; - - public Classifier(ITextBuffer buffer, IClassificationType errorOutputType) - { - _errorOutputType = errorOutputType; - _buffer = buffer; - } - - public IList GetClassificationSpans(SnapshotSpan span) - { - SortedSpans errorSpans; - if (!_buffer.Properties.TryGetProperty(s_textBufferPropertyKey, out errorSpans)) - { - return Array.Empty(); - } - - List classifications = new List(); - - foreach (var overlap in errorSpans.GetOverlap(span.Span)) - { - classifications.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, overlap), _errorOutputType)); - } - - return classifications; - } - - public event EventHandler ClassificationChanged - { - add { } - remove { } - } - } - - private static class FormatDefinitions - { - [Export(typeof(EditorFormatDefinition))] - [ClassificationType(ClassificationTypeNames = Name)] - [Name(Name)] - [DisplayName(Name)] - [UserVisible(true)] - internal sealed class ErrorOutput : ClassificationFormatDefinition - { - public const string Name = "Interactive Window Error Output"; - - [Export] - [Name(Name)] - [BaseDefinition(PredefinedClassificationTypeNames.NaturalLanguage)] - internal static readonly ClassificationTypeDefinition Definition = null; - - public ErrorOutput() - { - this.ForegroundColor = Color.FromRgb(0xff, 0, 0); - } - } - } - } -} diff --git a/src/InteractiveWindow/Editor/Output/OutputWriter.cs b/src/InteractiveWindow/Editor/Output/OutputWriter.cs deleted file mode 100644 index 1e8c4ddbd0a90..0000000000000 --- a/src/InteractiveWindow/Editor/Output/OutputWriter.cs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Text; -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal sealed class InteractiveWindowWriter : TextWriter - { - private readonly IInteractiveWindow _window; - private readonly SortedSpans _spans; - - internal InteractiveWindowWriter(IInteractiveWindow window, SortedSpans spans) - { - Debug.Assert(window != null); - _window = window; - _spans = spans; - } - - public IInteractiveWindow Window - { - get { return _window; } - } - - public SortedSpans Spans - { - get - { - return _spans; - } - } - - public override object InitializeLifetimeService() - { - return null; - } - - public override IFormatProvider FormatProvider - { - get { return CultureInfo.CurrentCulture; } - } - - public override Encoding Encoding - { - get { return Encoding.UTF8; } - } - - public override void Write(string value) - { - if (string.IsNullOrEmpty(value)) - { - return; - } - - int offset = _window.Write(value).Start; - if (_spans != null) - { - _spans.Add(new Span(offset, value.Length)); - } - } - - public override void Write(char[] value, int start, int count) - { - Write(new string(value, start, count)); - } - - public override void WriteLine() - { - Span span = _window.WriteLine(text: null); - if (_spans != null) - { - _spans.Add(span); - } - } - - public override void WriteLine(string str) - { - Span span = _window.WriteLine(str); - if (_spans != null) - { - _spans.Add(span); - } - } - } -} diff --git a/src/InteractiveWindow/Editor/Output/ResizingAdorner.cs b/src/InteractiveWindow/Editor/Output/ResizingAdorner.cs deleted file mode 100644 index a56e4d904ead0..0000000000000 --- a/src/InteractiveWindow/Editor/Output/ResizingAdorner.cs +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Windows; -using System.Windows.Controls.Primitives; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal sealed class ResizingAdorner : Adorner - { - private readonly VisualCollection _visualChildren; - private readonly Thumb _bottomRight; - - public ResizingAdorner(UIElement adornedElement) - : base(adornedElement) - { - _visualChildren = new VisualCollection(this); - _bottomRight = BuildAdornerCorner(Cursors.SizeNWSE, HandleBottomRight); - } - - private Thumb BuildAdornerCorner(Cursor cursor, DragDeltaEventHandler dragHandler) - { - var thumb = new Thumb(); - - // TODO: this thumb should be styled to look like a dotted triangle, - // similar to the one you can see on the bottom right corner of - // Internet Explorer window - thumb.Cursor = cursor; - thumb.Height = thumb.Width = 10; - thumb.Opacity = 0.40; - thumb.Background = new SolidColorBrush(Colors.MediumBlue); - thumb.DragDelta += dragHandler; - thumb.DragStarted += (s, e) => - { - ResizeStarted?.Invoke(this, e); - }; - thumb.DragCompleted += (s, e) => - { - ResizeCompleted?.Invoke(this, e); - }; - _visualChildren.Add(thumb); - return thumb; - } - - private void HandleBottomRight(object sender, DragDeltaEventArgs eventArgs) - { - var thumb = sender as Thumb; - var element = AdornedElement as FrameworkElement; - if (element == null || thumb == null) - { - return; - } - - element.MaxWidth = Math.Max(element.MaxWidth + eventArgs.HorizontalChange, thumb.DesiredSize.Width); - element.MaxHeight = Math.Max(element.MaxHeight + eventArgs.VerticalChange, thumb.DesiredSize.Height); - var size = new Size(element.MaxWidth, element.MaxHeight); - AdornedElement.Measure(size); - } - - protected override Size ArrangeOverride(Size finalSize) - { - var desiredWidth = AdornedElement.DesiredSize.Width; - var desiredHeight = AdornedElement.DesiredSize.Height; - var adornerWidth = DesiredSize.Width; - var adornerHeight = DesiredSize.Height; - - _bottomRight.Arrange(new Rect((desiredWidth - adornerWidth) / 2, - (desiredHeight - adornerHeight) / 2, adornerWidth, adornerHeight)); - - return finalSize; - } - - protected override int VisualChildrenCount - { - get { return _visualChildren.Count; } - } - - protected override Visual GetVisualChild(int index) - { - return _visualChildren[index]; - } - - public event RoutedEventHandler ResizeStarted; - public event RoutedEventHandler ResizeCompleted; - } -} diff --git a/src/InteractiveWindow/Editor/Output/SortedSpans.cs b/src/InteractiveWindow/Editor/Output/SortedSpans.cs deleted file mode 100644 index c8b099ae0d58f..0000000000000 --- a/src/InteractiveWindow/Editor/Output/SortedSpans.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - // TODO (tomat): could we avoid locking by using an ImmutableList? - - /// - /// Thread safe sequence of disjoint spans ordered by start position. - /// - internal sealed class SortedSpans - { - private readonly object _mutex = new object(); - private List _spans = new List(); - - public void Clear() - { - _spans = new List(); - } - - public void Add(Span span) - { - Debug.Assert(_spans.Count == 0 || span.Start >= _spans.Last().End); - Debug.Assert(span.Length > 0); - - lock (_mutex) - { - int last = _spans.Count - 1; - if (last >= 0 && _spans[last].End == span.Start) - { - // merge adjacent spans: - _spans[last] = new Span(_spans[last].Start, _spans[last].Length + span.Length); - } - else - { - _spans.Add(span); - } - } - } - - public IEnumerable GetOverlap(Span span) - { - List result = null; - var comparer = SpanStartComparer.Instance; - - lock (_mutex) - { - var count = _spans.Count; - - // _span is empty, no overlap. - if (count == 0) - { - return Enumerable.Empty(); - } - - int startIndex = _spans.BinarySearch(span, comparer); - - // If span is not found in _span, BinarySearch returns a negative number that is the - // bitwise complement of the index of the next span with larger starting index, or if - // there is no such span, the bitwise complement of _span.Count. - - // Try get the span before the one with next larger starting index on in the list, - // unless the first span is the next larger one, then we just get the first one. - if (startIndex < 0) - { - startIndex = ~startIndex; - - if (startIndex > 0) - { - startIndex = startIndex - 1; - } - } - - Debug.Assert(startIndex >= 0); - - int spanEnd = span.End; - for (int i = startIndex; i < count && _spans[i].Start < spanEnd; i++) - { - var overlap = span.Overlap(_spans[i]); - if (overlap.HasValue) - { - if (result == null) - { - result = new List(); - } - - result.Add(overlap.Value); - } - } - } - - return result ?? Enumerable.Empty(); - } - - private sealed class SpanStartComparer : IComparer - { - internal static readonly SpanStartComparer Instance = new SpanStartComparer(); - - public int Compare(Span x, Span y) - { - return x.Start - y.Start; - } - } - } -} diff --git a/src/InteractiveWindow/Editor/Output/ZoomableInlineAdornment.cs b/src/InteractiveWindow/Editor/Output/ZoomableInlineAdornment.cs deleted file mode 100644 index 37f647f18a1c1..0000000000000 --- a/src/InteractiveWindow/Editor/Output/ZoomableInlineAdornment.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Documents; -using System.Windows.Input; -using Microsoft.VisualStudio.Text.Editor; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal sealed class ZoomableInlineAdornment : ContentControl - { - private readonly ITextView _parent; - private readonly double _minimizedZoom; - private readonly double _zoomStep; - private readonly double _widthRatio; - private readonly double _heightRatio; - - private ResizingAdorner _adorner; - private bool _isResizing; - private double _zoom; - - public ZoomableInlineAdornment(UIElement content, ITextView parent) - { - _parent = parent; - Debug.Assert(parent is IInputElement); - this.Content = new Border { BorderThickness = new Thickness(1), Child = content, Focusable = true }; - - _zoom = 1.0; // config.GetConfig().Repl.InlineMedia.MaximizedZoom - _zoomStep = 0.25; // config.GetConfig().Repl.InlineMedia.ZoomStep - _minimizedZoom = 0.25; // config.GetConfig().Repl.InlineMedia.MinimizedZoom - _widthRatio = 0.67; // config.GetConfig().Repl.InlineMedia.WidthRatio - _heightRatio = 0.5; // config.GetConfig().Repl.InlineMedia.HeightRatio - - _isResizing = false; - UpdateSize(); - - this.PreviewMouseLeftButtonDown += (s, e) => - { - if (MyContent.IsFocused) - { - Keyboard.Focus(MyParent); - e.Handled = true; - } - }; - - this.MouseRightButtonDown += (s, e) => - { - // The editor doesn't support context menus, so even for an - // adornment we have to open it explicitly - ContextMenu.IsOpen = true; - }; - - this.GotFocus += OnGotFocus; - this.LostFocus += OnLostFocus; - - ContextMenu = MakeContextMenu(); - - var trigger = new Trigger { Property = IsFocusedProperty, Value = true }; - var setter = new Setter { Property = Border.BorderBrushProperty, Value = SystemColors.ActiveBorderBrush }; - trigger.Setters.Add(setter); - - var style = new Style(); - style.Triggers.Add(trigger); - this.MyContent.Style = style; - } - - private ContextMenu MakeContextMenu() - { - var result = new ContextMenu(); - AddMenuItem(result, "Zoom In", "Ctrl+OemPlus", (s, e) => OnZoomIn()); - AddMenuItem(result, "Zoom Out", "Ctrl+OemMinus", (s, e) => OnZoomOut()); - result.Items.Add(new Separator()); - AddMenuItem(result, "150%", null, (s, e) => Zoom(1.5)); - AddMenuItem(result, "100%", null, (s, e) => Zoom(1.0)); - AddMenuItem(result, "75%", null, (s, e) => Zoom(0.75)); - AddMenuItem(result, "50%", null, (s, e) => Zoom(0.50)); - AddMenuItem(result, "25%", null, (s, e) => Zoom(0.25)); - return result; - } - - private static void AddMenuItem(ContextMenu menu, string text, string shortcut, EventHandler handler) - { - var item = new MenuItem(); - item.Header = text; - item.Click += (s, e) => handler(s, e); - menu.Items.Add(item); - } - - private Border MyContent - { - get { return Content as Border; } - } - - private IInputElement MyParent - { - get { return _parent as IInputElement; } - } - - private void OnGotFocus(object sender, RoutedEventArgs args) - { - MyParent.PreviewMouseLeftButtonDown += OnPreviewParentMouseDown; - PreviewKeyDown += OnPreviewKeyDown; - _adorner = new ResizingAdorner(MyContent); - _adorner.ResizeStarted += OnResizeStarted; - _adorner.ResizeCompleted += OnResizeCompleted; - - var adornerLayer = AdornerLayer.GetAdornerLayer(MyContent); - adornerLayer.Add(_adorner); - } - - private void OnLostFocus(object sender, RoutedEventArgs args) - { - MyParent.PreviewMouseLeftButtonDown -= OnPreviewParentMouseDown; - PreviewKeyDown -= OnPreviewKeyDown; - _adorner.ResizeStarted -= OnResizeStarted; - _adorner.ResizeCompleted -= OnResizeCompleted; - - var adornerLayer = AdornerLayer.GetAdornerLayer(MyContent); - adornerLayer.Remove(_adorner); - _adorner = null; - } - - private void OnPreviewKeyDown(object sender, KeyEventArgs args) - { - var modifiers = args.KeyboardDevice.Modifiers & ModifierKeys.Control; - if (modifiers == ModifierKeys.Control && args.Key == Key.OemPlus) - { - OnZoomIn(); - args.Handled = true; - } - else if (modifiers == ModifierKeys.Control && args.Key == Key.OemMinus) - { - OnZoomOut(); - args.Handled = true; - } - } - - private void OnPreviewParentMouseDown(object sender, RoutedEventArgs args) - { - if (MyContent.IsFocused) - { - Keyboard.Focus(MyParent); - } - } - - private void OnResizeStarted(object sender, RoutedEventArgs args) - { - _isResizing = true; - } - - private void OnResizeCompleted(object sender, RoutedEventArgs args) - { - _isResizing = false; - UpdateSize(); - } - - internal void Zoom(double zoomFactor) - { - _zoom = zoomFactor; - UpdateSize(); - } - - private void OnZoomIn() - { - _zoom += _zoomStep; - UpdateSize(); - } - - private void OnZoomOut() - { - if (_zoom - _zoomStep > 0.1) - { - _zoom -= _zoomStep; - UpdateSize(); - } - } - - internal void UpdateSize() - { - if (_isResizing) - { - return; - } - - double width = _parent.ViewportWidth * _widthRatio * _zoom; - double height = _parent.ViewportHeight * _heightRatio * _zoom; - MyContent.MaxWidth = width; - MyContent.MaxHeight = height; - MyContent.Measure(new Size(width, height)); - } - - internal double MinimizedZoom - { - get { return _minimizedZoom; } - } - } -} diff --git a/src/InteractiveWindow/Editor/PredefinedInteractiveContentTypes.cs b/src/InteractiveWindow/Editor/PredefinedInteractiveContentTypes.cs deleted file mode 100644 index b3a32a0935b2e..0000000000000 --- a/src/InteractiveWindow/Editor/PredefinedInteractiveContentTypes.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - public static class PredefinedInteractiveContentTypes - { - public const string InteractiveContentTypeName = "Interactive Content"; - public const string InteractiveOutputContentTypeName = "Interactive Output"; - } -} diff --git a/src/InteractiveWindow/Editor/PredefinedInteractiveTextViewRoles.cs b/src/InteractiveWindow/Editor/PredefinedInteractiveTextViewRoles.cs deleted file mode 100644 index 40936a6f6086f..0000000000000 --- a/src/InteractiveWindow/Editor/PredefinedInteractiveTextViewRoles.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - public static class PredefinedInteractiveTextViewRoles - { - /// - /// The additional role found in any REPL editor window. - /// - public const string InteractiveTextViewRole = "REPL"; - } -} diff --git a/src/InteractiveWindow/Editor/ProjectionBufferExtensions.cs b/src/InteractiveWindow/Editor/ProjectionBufferExtensions.cs deleted file mode 100644 index d0d20b73564f7..0000000000000 --- a/src/InteractiveWindow/Editor/ProjectionBufferExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Projection; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal static class ProjectionBufferExtensions - { - internal static SnapshotSpan GetSourceSpan(this IProjectionSnapshot snapshot, int index) - { - return snapshot.GetSourceSpans(index, 1)[0]; - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/PublicAPI.Shipped.txt b/src/InteractiveWindow/Editor/PublicAPI.Shipped.txt deleted file mode 100644 index f334e55c105a9..0000000000000 --- a/src/InteractiveWindow/Editor/PublicAPI.Shipped.txt +++ /dev/null @@ -1,111 +0,0 @@ -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand.ClassifyArguments(Microsoft.VisualStudio.Text.ITextSnapshot snapshot, Microsoft.VisualStudio.Text.Span argumentsSpan, Microsoft.VisualStudio.Text.Span spanToClassify) -> System.Collections.Generic.IEnumerable -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand.CommandLine.get -> string -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand.Description.get -> string -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand.DetailedDescription.get -> System.Collections.Generic.IEnumerable -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand.Execute(Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow window, string arguments) -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand.Names.get -> System.Collections.Generic.IEnumerable -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand.ParametersDescription.get -> System.Collections.Generic.IEnumerable> -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.Classify(Microsoft.VisualStudio.Text.SnapshotSpan span) -> System.Collections.Generic.IEnumerable -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.CommandPrefix.get -> string -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.DisplayCommandHelp(Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand command) -> void -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.DisplayCommandUsage(Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand command, System.IO.TextWriter writer, bool displayDetails) -> void -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.DisplayHelp() -> void -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.GetCommands() -> System.Collections.Generic.IEnumerable -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.InCommand.get -> bool -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.TryExecuteCommand() -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands.this[string name].get -> Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommand -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommandsFactory -Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommandsFactory.CreateInteractiveCommands(Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow window, string prefix, System.Collections.Generic.IEnumerable commands) -> Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands -Microsoft.VisualStudio.InteractiveWindow.Commands.InteractiveWindowCommandExtensions -Microsoft.VisualStudio.InteractiveWindow.Commands.PredefinedInteractiveCommandsContentTypes -Microsoft.VisualStudio.InteractiveWindow.ExecutionResult -Microsoft.VisualStudio.InteractiveWindow.ExecutionResult.ExecutionResult(bool isSuccessful) -> void -Microsoft.VisualStudio.InteractiveWindow.ExecutionResult.IsSuccessful.get -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.AbortExecution() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.CanExecuteCode(string text) -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.CurrentWindow.get -> Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.CurrentWindow.set -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.ExecuteCodeAsync(string text) -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.FormatClipboard() -> string -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.GetPrompt() -> string -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.InitializeAsync() -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator.ResetAsync(bool initialize = true) -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.AddInput(string input) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.Close() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.CurrentLanguageBuffer.get -> Microsoft.VisualStudio.Text.ITextBuffer -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.ErrorOutputWriter.get -> System.IO.TextWriter -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.Evaluator.get -> Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.FlushOutput() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.InitializeAsync() -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.InsertCode(string text) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.IsInitializing.get -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.IsResetting.get -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.IsRunning.get -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.Operations.get -> Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.OutputBuffer.get -> Microsoft.VisualStudio.Text.ITextBuffer -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.OutputWriter.get -> System.IO.TextWriter -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.ReadStandardInput() -> System.IO.TextReader -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.ReadyForInput -> System.Action -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.SubmissionBufferAdded -> System.EventHandler -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.SubmitAsync(System.Collections.Generic.IEnumerable inputs) -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.TextView.get -> Microsoft.VisualStudio.Text.Editor.IWpfTextView -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.Write(System.Windows.UIElement element) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.Write(string text) -> Microsoft.VisualStudio.Text.Span -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.WriteError(string text) -> Microsoft.VisualStudio.Text.Span -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.WriteErrorLine(string text) -> Microsoft.VisualStudio.Text.Span -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow.WriteLine(string text) -> Microsoft.VisualStudio.Text.Span -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow2 -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow2.AddToHistory(string input) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowEditorFactoryService -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow window) -> Microsoft.VisualStudio.Text.ITextBuffer -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowEditorFactoryService.CreateTextView(Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow window, Microsoft.VisualStudio.Text.ITextBuffer buffer, Microsoft.VisualStudio.Text.Editor.ITextViewRoleSet roles) -> Microsoft.VisualStudio.Text.Editor.IWpfTextView -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowFactoryService -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowFactoryService.CreateWindow(Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator evaluator) -> Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.Backspace() -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.BreakLine() -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.Cancel() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.ClearHistory() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.ClearView() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.Cut() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.Delete() -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.End(bool extendSelection) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.ExecuteInput() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.HistoryNext(string search = null) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.HistoryPrevious(string search = null) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.HistorySearchNext() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.HistorySearchPrevious() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.Home(bool extendSelection) -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.Paste() -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.ResetAsync(bool initialize = true) -> System.Threading.Tasks.Task -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.Return() -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.SelectAll() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations.TrySubmitStandardInput() -> bool -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations2 -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations2.Copy() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations2.CopyCode() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations2.CutLine() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations2.DeleteLine() -> void -Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindowOperations2.TypeChar(char typedChar) -> void -Microsoft.VisualStudio.InteractiveWindow.InteractiveWindowExtensions -Microsoft.VisualStudio.InteractiveWindow.InteractiveWindowOptions -Microsoft.VisualStudio.InteractiveWindow.PredefinedInteractiveContentTypes -Microsoft.VisualStudio.InteractiveWindow.PredefinedInteractiveTextViewRoles -Microsoft.VisualStudio.InteractiveWindow.SubmissionBufferAddedEventArgs -Microsoft.VisualStudio.InteractiveWindow.SubmissionBufferAddedEventArgs.NewBuffer.get -> Microsoft.VisualStudio.Text.ITextBuffer -Microsoft.VisualStudio.InteractiveWindow.SubmissionBufferAddedEventArgs.SubmissionBufferAddedEventArgs(Microsoft.VisualStudio.Text.ITextBuffer newBuffer) -> void -const Microsoft.VisualStudio.InteractiveWindow.Commands.PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName = "Interactive Command" -> string -const Microsoft.VisualStudio.InteractiveWindow.PredefinedInteractiveContentTypes.InteractiveContentTypeName = "Interactive Content" -> string -const Microsoft.VisualStudio.InteractiveWindow.PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName = "Interactive Output" -> string -const Microsoft.VisualStudio.InteractiveWindow.PredefinedInteractiveTextViewRoles.InteractiveTextViewRole = "REPL" -> string -static Microsoft.VisualStudio.InteractiveWindow.Commands.InteractiveWindowCommandExtensions.GetInteractiveCommands(this Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow window) -> Microsoft.VisualStudio.InteractiveWindow.Commands.IInteractiveWindowCommands -static Microsoft.VisualStudio.InteractiveWindow.InteractiveWindowExtensions.GetInteractiveWindow(this Microsoft.VisualStudio.Text.ITextBuffer buffer) -> Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow -static Microsoft.VisualStudio.InteractiveWindow.InteractiveWindowOptions.SmartUpDown.get -> Microsoft.VisualStudio.Text.Editor.EditorOptionKey -static readonly Microsoft.VisualStudio.InteractiveWindow.ExecutionResult.Failed -> System.Threading.Tasks.Task -static readonly Microsoft.VisualStudio.InteractiveWindow.ExecutionResult.Failure -> Microsoft.VisualStudio.InteractiveWindow.ExecutionResult -static readonly Microsoft.VisualStudio.InteractiveWindow.ExecutionResult.Succeeded -> System.Threading.Tasks.Task -static readonly Microsoft.VisualStudio.InteractiveWindow.ExecutionResult.Success -> Microsoft.VisualStudio.InteractiveWindow.ExecutionResult diff --git a/src/InteractiveWindow/Editor/PublicAPI.Unshipped.txt b/src/InteractiveWindow/Editor/PublicAPI.Unshipped.txt deleted file mode 100644 index c7b41f5cb530b..0000000000000 --- a/src/InteractiveWindow/Editor/PublicAPI.Unshipped.txt +++ /dev/null @@ -1,3 +0,0 @@ -Microsoft.VisualStudio.InteractiveWindow.InteractiveClipboardFormat -const Microsoft.VisualStudio.InteractiveWindow.InteractiveClipboardFormat.Tag = "89344A36-9821-495A-8255-99A63969F87D" -> string -static Microsoft.VisualStudio.InteractiveWindow.InteractiveClipboardFormat.Deserialize(object value) -> string \ No newline at end of file diff --git a/src/InteractiveWindow/Editor/ReplInput.cs b/src/InteractiveWindow/Editor/ReplInput.cs deleted file mode 100644 index b0b5de298229e..0000000000000 --- a/src/InteractiveWindow/Editor/ReplInput.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Diagnostics; -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - [DebuggerDisplay("{GetDebuggerDisplay()}")] - internal struct ReplSpan - { - // CustomTrackingSpan or string - public object Span { get; } - public ReplSpanKind Kind { get; } - public int LineNumber { get; } - - public ReplSpan(CustomTrackingSpan span, ReplSpanKind kind, int lineNumber) - : this((object)span, kind, lineNumber) - { - Debug.Assert(!kind.IsPrompt()); - } - - public ReplSpan(string literal, ReplSpanKind kind, int lineNumber) - : this((object)literal, kind, lineNumber) - { - } - - private ReplSpan(object span, ReplSpanKind kind, int lineNumber) - { - this.Span = span; - this.Kind = kind; - this.LineNumber = lineNumber; - } - - public CustomTrackingSpan TrackingSpan => (CustomTrackingSpan)Span; - - public ReplSpan WithEndTrackingMode(PointTrackingMode endTrackingMode) - { - return new ReplSpan(((CustomTrackingSpan)this.Span).WithEndTrackingMode(endTrackingMode), this.Kind, this.LineNumber); - } - - public ReplSpan WithLineNumber(int lineNumber) - { - return new ReplSpan(this.Span, this.Kind, lineNumber); - } - - public int Length - { - get - { - var value = Span as string; - return (value != null) ? value.Length : TrackingSpan.GetSpan(TrackingSpan.TextBuffer.CurrentSnapshot).Length; - } - } - - private string GetDebuggerDisplay() - { - return $"Line {LineNumber}: {Kind} - {Span}"; - } - } -} diff --git a/src/InteractiveWindow/Editor/Resources/ReplToolBarImages.bmp b/src/InteractiveWindow/Editor/Resources/ReplToolBarImages.bmp deleted file mode 100644 index e1d15a1335f27..0000000000000 Binary files a/src/InteractiveWindow/Editor/Resources/ReplToolBarImages.bmp and /dev/null differ diff --git a/src/InteractiveWindow/Editor/SmartIndent/InteractiveSmartIndenter.cs b/src/InteractiveWindow/Editor/SmartIndent/InteractiveSmartIndenter.cs deleted file mode 100644 index 3494c3660a943..0000000000000 --- a/src/InteractiveWindow/Editor/SmartIndent/InteractiveSmartIndenter.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal sealed class InteractiveSmartIndenter : ISmartIndent - { - private readonly IContentType _contentType; - private readonly ITextView _view; - private readonly ISmartIndent _indenter; - - internal static InteractiveSmartIndenter Create( - IEnumerable> smartIndenterProviders, - IContentType contentType, - ITextView view) - { - var provider = GetProvider(smartIndenterProviders, contentType); - return (provider == null) ? null : new InteractiveSmartIndenter(contentType, view, provider.Item2.Value); - } - - private InteractiveSmartIndenter(IContentType contentType, ITextView view, ISmartIndentProvider provider) - { - _contentType = contentType; - _view = view; - _indenter = provider.CreateSmartIndent(view); - } - - public int? GetDesiredIndentation(ITextSnapshotLine line) - { - // get point at the subject buffer - var mappingPoint = _view.BufferGraph.CreateMappingPoint(line.Start, PointTrackingMode.Negative); - - // TODO (https://github.com/dotnet/roslyn/issues/5281): Remove try-catch. - SnapshotPoint? point = null; - try - { - point = mappingPoint.GetInsertionPoint(b => b.ContentType.IsOfType(_contentType.TypeName)); - } - catch (ArgumentOutOfRangeException) - { - // Suppress this to work around DevDiv #144964. - // Note: Other callers might be affected, but this is the narrowest workaround for the observed problems. - // A fix is already being reviewed, so a broader change is not required. - return null; - } - - if (!point.HasValue) - { - return null; - } - - // Currently, interactive smart indenter returns indentation based - // solely on subject buffer's information and doesn't consider spaces - // in interactive window itself. Note: This means the ITextBuffer passed - // to ISmartIndent.GetDesiredIndentation is not this.view.TextBuffer. - return _indenter.GetDesiredIndentation(point.Value.GetContainingLine()); - } - - public void Dispose() - { - _indenter.Dispose(); - } - - // Returns the provider that supports the most derived content type. - // If there are two providers that support the same content type, or - // two providers that support different content types that do not have - // inheritance relationship, we simply return the first we encounter. - private static Tuple> GetProvider( - IEnumerable> smartIndenterProviders, - IContentType contentType) - { - // If there are two providers that both support the - // same content type, we simply choose the first. - var provider = smartIndenterProviders.FirstOrDefault(p => p.Metadata.ContentTypes.Contains(contentType.TypeName)); - if (provider != null) - { - return Tuple.Create(contentType, provider); - } - - Tuple> bestPair = null; - foreach (var baseType in contentType.BaseTypes) - { - var pair = GetProvider(smartIndenterProviders, baseType); - if ((pair != null) && ((bestPair == null) || IsBaseContentType(pair.Item1, bestPair.Item1))) - { - bestPair = pair; - } - } - - return bestPair; - } - - // Returns true if the second content type is a base type of the first. - private static bool IsBaseContentType(IContentType type, IContentType potentialBase) - { - return type.BaseTypes.Any(b => b.IsOfType(potentialBase.TypeName) || IsBaseContentType(b, potentialBase)); - } - } -} diff --git a/src/InteractiveWindow/Editor/SmartIndent/InteractiveSmartIndenterProvider.cs b/src/InteractiveWindow/Editor/SmartIndent/InteractiveSmartIndenterProvider.cs deleted file mode 100644 index e3208322e7215..0000000000000 --- a/src/InteractiveWindow/Editor/SmartIndent/InteractiveSmartIndenterProvider.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - [Export(typeof(ISmartIndentProvider))] - [ContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName)] - internal class InteractiveSmartIndenterProvider : ISmartIndentProvider - { - private readonly ITextEditorFactoryService _editorFactory; - private readonly IEnumerable> _indentProviders; - - [ImportingConstructor] - public InteractiveSmartIndenterProvider( - ITextEditorFactoryService editorFactory, - [ImportMany] IEnumerable> indentProviders) - { - if (editorFactory == null) - { - throw new ArgumentNullException(nameof(editorFactory)); - } - - if (indentProviders == null) - { - throw new ArgumentNullException(nameof(indentProviders)); - } - - _editorFactory = editorFactory; - _indentProviders = indentProviders; - } - - public ISmartIndent CreateSmartIndent(ITextView view) - { - var window = view.TextBuffer.GetInteractiveWindow(); - if (window == null || window.CurrentLanguageBuffer == null) - { - return null; - } - - return InteractiveSmartIndenter.Create(_indentProviders, window.CurrentLanguageBuffer.ContentType, view); - } - } -} diff --git a/src/InteractiveWindow/Editor/SmartUpDownOption.cs b/src/InteractiveWindow/Editor/SmartUpDownOption.cs deleted file mode 100644 index e40aaa51a73fa..0000000000000 --- a/src/InteractiveWindow/Editor/SmartUpDownOption.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - [Export(typeof(EditorOptionDefinition))] - [Name(OptionName)] - internal sealed class SmartUpDownOption : EditorOptionDefinition - { - internal const string OptionName = "InteractiveSmartUpDown"; - - public override EditorOptionKey Key - { - get - { - return InteractiveWindowOptions.SmartUpDown; - } - } - } -} diff --git a/src/InteractiveWindow/Editor/SubmissionBufferAddedEventArgs.cs b/src/InteractiveWindow/Editor/SubmissionBufferAddedEventArgs.cs deleted file mode 100644 index 55b9dc3427f72..0000000000000 --- a/src/InteractiveWindow/Editor/SubmissionBufferAddedEventArgs.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - public sealed class SubmissionBufferAddedEventArgs : EventArgs - { - private readonly ITextBuffer _newBuffer; - - public SubmissionBufferAddedEventArgs(ITextBuffer newBuffer) - { - if (newBuffer == null) - { - throw new ArgumentNullException(nameof(newBuffer)); - } - - _newBuffer = newBuffer; - } - - public ITextBuffer NewBuffer - { - get - { - return _newBuffer; - } - } - } -} diff --git a/src/InteractiveWindow/Editor/TextTransactionMergePolicy.cs b/src/InteractiveWindow/Editor/TextTransactionMergePolicy.cs deleted file mode 100644 index e5c72a43e39fb..0000000000000 --- a/src/InteractiveWindow/Editor/TextTransactionMergePolicy.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.VisualStudio.Text.Operations; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - // The code here is copied from `Microsoft.VisualStudio.Text.Operations.Implementation` - // with minor modification to provide ability for merging undo transactions in InteractiveWindow . - - [Flags] - internal enum TextTransactionMergeDirections - { - Forward = 0x0001, - Backward = 0x0002 - } - - /// - /// This is the merge policy used for determining whether text's undo transactions can be merged. - /// - internal class TextTransactionMergePolicy : IMergeTextUndoTransactionPolicy - { - private TextTransactionMergeDirections _allowableMergeDirections; - - public TextTransactionMergePolicy() : this(TextTransactionMergeDirections.Forward | TextTransactionMergeDirections.Backward) - { - } - - public TextTransactionMergePolicy(TextTransactionMergeDirections allowableMergeDirections) - { - _allowableMergeDirections = allowableMergeDirections; - } - - public bool CanMerge(ITextUndoTransaction newTransaction, ITextUndoTransaction oldTransaction) - { - // Validate - if (newTransaction == null) - { - throw new ArgumentNullException(nameof(newTransaction)); - } - - if (oldTransaction == null) - { - throw new ArgumentNullException(nameof(oldTransaction)); - } - - TextTransactionMergePolicy oldPolicy = oldTransaction.MergePolicy as TextTransactionMergePolicy; - TextTransactionMergePolicy newPolicy = newTransaction.MergePolicy as TextTransactionMergePolicy; - if (oldPolicy == null || newPolicy == null) - { - throw new InvalidOperationException("The MergePolicy for both transactions should be a TextTransactionMergePolicy."); - } - - // Make sure the merge policy directions permit merging these two transactions. - if ((oldPolicy._allowableMergeDirections & TextTransactionMergeDirections.Forward) == 0 || - (newPolicy._allowableMergeDirections & TextTransactionMergeDirections.Backward) == 0) - { - return false; - } - - // Only merge text transactions that have the same description - if (newTransaction.Description != oldTransaction.Description) - { - return false; - } - - return true; - } - - public void PerformTransactionMerge(ITextUndoTransaction existingTransaction, ITextUndoTransaction newTransaction) - { - if (existingTransaction == null) - { - throw new ArgumentNullException(nameof(existingTransaction)); - } - if (newTransaction == null) - { - throw new ArgumentNullException(nameof(newTransaction)); - } - - // Remove trailing AfterTextBufferChangeUndoPrimitive from previous transaction and skip copying - // initial BeforeTextBufferChangeUndoPrimitive from newTransaction, as they are unnecessary. - int copyStartIndex = 0; - - // Copy items from newTransaction into existingTransaction. - for (int i = copyStartIndex; i < newTransaction.UndoPrimitives.Count; i++) - { - existingTransaction.UndoPrimitives.Add(newTransaction.UndoPrimitives[i]); - } - } - - public bool TestCompatiblePolicy(IMergeTextUndoTransactionPolicy other) - { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - - // Only merge transaction if they are both a text transaction - return this.GetType() == other.GetType(); - } - } -} diff --git a/src/InteractiveWindow/Editor/Utils/Contract.cs b/src/InteractiveWindow/Editor/Utils/Contract.cs deleted file mode 100644 index 6631fbc96918e..0000000000000 --- a/src/InteractiveWindow/Editor/Utils/Contract.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal static class Contract - { - [DebuggerDisplay("Unreachable")] - public static Exception Unreachable - { - get - { - Debug.Fail("This code path should not be reachable"); - return new InvalidOperationException(); - } - } - } -} diff --git a/src/InteractiveWindow/Editor/Utils/EditorExtensions.cs b/src/InteractiveWindow/Editor/Utils/EditorExtensions.cs deleted file mode 100644 index 420e1d0e6febd..0000000000000 --- a/src/InteractiveWindow/Editor/Utils/EditorExtensions.cs +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.Text; - -namespace Microsoft.VisualStudio.InteractiveWindow -{ - internal static class EditorExtensions - { - internal static bool EndsWithLineBreak(this ITextSnapshot snapshot) - { - int length = snapshot.Length; - return length > 0 && (snapshot[length - 1] == '\n' || snapshot[length - 1] == '\r'); - } - - internal static bool EndsWith(this ITextSnapshot snapshot, char c) - { - int length = snapshot.Length; - return length > 0 && snapshot[length - 1] == c; - } - - internal static bool EndsWithLineBreak(this string str) - { - int length = str.Length; - return length > 0 && (str[length - 1] == '\n' || str[length - 1] == '\r'); - } - - internal static bool StartsWith(this SnapshotSpan span, string prefix) - { - if (span.Length < prefix.Length) - { - return false; - } - - var snapshot = span.Snapshot; - int start = span.Start.Position; - for (int i = 0; i < prefix.Length; i++) - { - if (snapshot[start + i] != prefix[i]) - { - return false; - } - } - - return true; - } - - internal static SnapshotSpan Trim(this SnapshotSpan snapshotSpan) - { - return snapshotSpan.TrimStart().TrimEnd(); - } - - internal static SnapshotSpan TrimStart(this SnapshotSpan snapshotSpan) - { - var snapshot = snapshotSpan.Snapshot; - - int i = snapshotSpan.Start.Position; - int end = snapshotSpan.End.Position; - while (i < end && char.IsWhiteSpace(snapshot[i])) - { - i++; - } - - return new SnapshotSpan(snapshotSpan.Snapshot, Span.FromBounds(i, end)); - } - - internal static SnapshotSpan TrimEnd(this SnapshotSpan snapshotSpan) - { - var snapshot = snapshotSpan.Snapshot; - - int i = snapshotSpan.End - 1; - int start = snapshotSpan.Start; - while (i >= start && char.IsWhiteSpace(snapshot[i])) - { - i--; - } - - return new SnapshotSpan(snapshotSpan.Snapshot, Span.FromBounds(start, i + 1)); - } - - internal static int IndexOfAnyWhiteSpace(this string str) - { - for (int i = 0; i < str.Length; i++) - { - if (char.IsWhiteSpace(str[i])) - { - return i; - } - } - - return -1; - } - - internal static SnapshotPoint? IndexOfAnyWhiteSpace(this SnapshotSpan snapshotSpan) - { - var snapshot = snapshotSpan.Snapshot; - int i = snapshotSpan.Start; - int end = snapshotSpan.End; - while (i < end) - { - if (char.IsWhiteSpace(snapshot[i])) - { - return new SnapshotPoint(snapshotSpan.Snapshot, i); - } - - i++; - } - - return null; - } - - internal static SnapshotSpan GetExtent(this ITextSnapshot snapshot) - { - return new SnapshotSpan(snapshot, 0, snapshot.Length); - } - - internal static SnapshotSpan SubSpan(this SnapshotSpan span, int start) - { - return new SnapshotSpan(span.Snapshot, Span.FromBounds(span.Start.Position + start, span.End.Position)); - } - - internal static SnapshotSpan SubSpan(this SnapshotSpan span, int start, int length) - { - return new SnapshotSpan(span.Snapshot, span.Start.Position + start, length); - } - - internal static void GetLineAndColumn(this VirtualSnapshotPoint point, out ITextSnapshotLine line, out int column) - { - line = point.Position.GetContainingLine(); - column = point.Position.Position - line.Start.Position + point.VirtualSpaces; - } - - internal static void GetLineAndColumn(this SnapshotPoint point, out ITextSnapshotLine line, out int column) - { - line = point.GetContainingLine(); - column = point.Position - line.Start.Position; - } - } -} diff --git a/src/InteractiveWindow/Editor/project.json b/src/InteractiveWindow/Editor/project.json deleted file mode 100644 index f806648017d69..0000000000000 --- a/src/InteractiveWindow/Editor/project.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "dependencies": { - "Microsoft.VisualStudio.Text.Data": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Text.Logic": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Text.UI": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Text.UI.Wpf": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "RoslynDependencies.Microsoft.VisualStudio.Text.Internal": "14.3.25407", - "Microsoft.VisualStudio.ImageCatalog": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Language.StandardClassification": "14.3.25407", - "Microsoft.VisualStudio.Imaging": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Language.Intellisense": { - "version": "14.3.25407", - "suppressParent": "all" - } - }, - "frameworks": { - "net46": { } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/EditorTest/EventListenerGuard.cs b/src/InteractiveWindow/EditorTest/EventListenerGuard.cs deleted file mode 100644 index e9b09704f6890..0000000000000 --- a/src/InteractiveWindow/EditorTest/EventListenerGuard.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Roslyn.Test.Utilities; -using System; -using System.Collections.Concurrent; -using Xunit; - -namespace Microsoft.CodeAnalysis.UnitTests -{ - public class EventListenerGuard - { - /// - /// A unit test that guards against the EventListener race condition: - /// - /// - https://github.com/dotnet/roslyn/issues/8936 - /// - https://github.com/dotnet/corefx/issues/3793 - /// - /// The underlying issue here is EventListener.DisposeOnShutdown has a race - /// condition if a new EventSource is added during an AppDomain or Process - /// exit. When this occurs there is an unhandled exception during shutdown - /// due to a modified collection during enumeration that causes xunit to - /// falsely fail the run. - /// - /// The type CDSCollectionETWBCLProvider triggers this bug in our tests. It - /// is an EventSource for concurrent collections that is loaded on many - /// concurrent collection operations. These operations are not triggered - /// directly in some of our tests and hence lead to the race. - /// - /// This test guards against them force loading, albeit indirectly, the EventSource - /// instance of CDSCollectionETWBCLProvider. Hence uses during shutdown - /// are just re-using this instance and don't trigger the race. - /// - [WorkItem(8936, "https://github.com/dotnet/roslyn/issues/8936")] - [Fact] - public void GuardAgainstRace() - { - // This code will trigger the load of CDSCollectionETWBCLProvider - var dictionary = new ConcurrentDictionary(); - dictionary.Clear(); - - var log = typeof(ConcurrentDictionary) - .Assembly - .GetType("System.Collections.Concurrent.CDSCollectionETWBCLProvider") - .GetField("Log", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) - .GetValue(null); - Assert.NotNull(log); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/HistoryTests.cs b/src/InteractiveWindow/EditorTest/HistoryTests.cs deleted file mode 100644 index cfec3447c0352..0000000000000 --- a/src/InteractiveWindow/EditorTest/HistoryTests.cs +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; -using Microsoft.VisualStudio.InteractiveWindow.Commands; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Text.Projection; -using Moq; -using Xunit; -using Roslyn.Test.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public class HistoryTests : IDisposable - { - private readonly InteractiveWindowTestHost _testHost; - private readonly ITextBuffer _buffer; - private readonly History _history; - - public HistoryTests() - { - _testHost = new InteractiveWindowTestHost(); - _buffer = _testHost.ExportProvider.GetExport().Value.CreateTextBuffer(); - _history = new History(); - } - - void IDisposable.Dispose() - { - _testHost.Dispose(); - } - - [WpfFact] - public void TestClear() - { - AddEntries("1", "2", "3"); - Assert.Equal(3, _history.Length); - Assert.Equal(3, HistoryEntries.Count()); - - _history.Clear(); - Assert.Equal(0, _history.Length); - Assert.Empty(HistoryEntries); - - AddEntries("1", "2"); - Assert.Equal(2, _history.Length); - Assert.Equal(2, HistoryEntries.Count()); - } - - [WpfFact] - public void TestMaxLength() - { - var buffer = _testHost.ExportProvider.GetExport().Value.CreateTextBuffer(); - buffer.Insert(0, "0123456789"); - var snapshot = buffer.CurrentSnapshot; - - var history = new History(maxLength: 0); - - history.Add(new SnapshotSpan(snapshot, new Span(0, 1))); - Assert.Empty(GetHistoryEntries(history)); - - history = new History(maxLength: 1); - history.Add(new SnapshotSpan(snapshot, new Span(0, 1))); - Assert.Equal(new[] { "0" }, GetHistoryEntries(history)); - history.Add(new SnapshotSpan(snapshot, new Span(1, 1))); - Assert.Equal(new[] { "1" }, GetHistoryEntries(history)); // Oldest entry is dropped. - - history = new History(maxLength: 2); - history.Add(new SnapshotSpan(snapshot, new Span(0, 1))); - Assert.Equal(new[] { "0" }, GetHistoryEntries(history)); - history.Add(new SnapshotSpan(snapshot, new Span(1, 1))); - Assert.Equal(new[] { "0", "1" }, GetHistoryEntries(history)); - history.Add(new SnapshotSpan(snapshot, new Span(2, 1))); - Assert.Equal(new[] { "1", "2" }, GetHistoryEntries(history)); // Oldest entry is dropped. - } - - [WpfFact] - public void TestLast() - { - for (int i = 0; i < 3; i++) - { - var text = i.ToString(); - AddEntries(text); - Assert.Equal(text, _history.Last.Text); - } - } - - [WpfFact] - public void TestForgetOriginalBuffers() - { - var entries = new[] { "1", "2", "3" }; - AddEntries(entries); - - Assert.Equal(entries, HistoryEntries); - AssertEx.All(_history.Items, e => e.OriginalSpan.HasValue); - - _history.ForgetOriginalBuffers(); - - Assert.Equal(entries, HistoryEntries); - AssertEx.None(_history.Items, e => e.OriginalSpan.HasValue); - } - - [WpfFact] - public void TestDuplicateEntries() - { - AddEntries("1", "1", "2", "2", "1", "2", "2", "1"); - Assert.Equal(new[] { "1", "2", "1", "2", "1" }, HistoryEntries); - } - - [WpfFact] - public void TestPrevious() - { - AddEntries("1", "2", "3"); - - CheckHistoryText(_history.GetPrevious(null), "3"); - CheckHistoryText(_history.GetPrevious(null), "2"); - CheckHistoryText(_history.GetPrevious(null), "1"); - CheckHistoryText(_history.GetPrevious(null), null); - CheckHistoryText(_history.GetPrevious(null), null); - } - - [WpfFact] - public void TestNext() - { - AddEntries("1", "2", "3"); - - CheckHistoryText(_history.GetNext(null), null); - CheckHistoryText(_history.GetNext(null), null); - CheckHistoryText(_history.GetPrevious(null), "3"); - CheckHistoryText(_history.GetPrevious(null), "2"); - CheckHistoryText(_history.GetPrevious(null), "1"); - CheckHistoryText(_history.GetPrevious(null), null); - CheckHistoryText(_history.GetNext(null), "2"); - CheckHistoryText(_history.GetNext(null), "3"); - CheckHistoryText(_history.GetNext(null), null); - CheckHistoryText(_history.GetNext(null), null); - } - - [WpfFact] - public void TestPreviousWithPattern_NoMatch() - { - AddEntries("123", "12", "1"); - - CheckHistoryText(_history.GetPrevious("4"), null); - CheckHistoryText(_history.GetPrevious("4"), null); - } - - [WpfFact] - public void TestPreviousWithPattern_PatternMaintained() - { - AddEntries("123", "12", "1"); - - CheckHistoryText(_history.GetPrevious("12"), "12"); // Skip over non-matching entry. - CheckHistoryText(_history.GetPrevious("12"), "123"); - CheckHistoryText(_history.GetPrevious("12"), null); - } - - [WpfFact] - public void TestPreviousWithPattern_PatternDropped() - { - AddEntries("1", "2", "3"); - - CheckHistoryText(_history.GetPrevious("2"), "2"); // Skip over non-matching entry. - CheckHistoryText(_history.GetPrevious(null), "1"); // Pattern isn't passed, so return to normal iteration. - CheckHistoryText(_history.GetPrevious(null), null); - } - - [WpfFact] - public void TestPreviousWithPattern_PatternChanged() - { - AddEntries("1a", "2a", "1b", "2b"); - - CheckHistoryText(_history.GetPrevious("1"), "1b"); // Skip over non-matching entry. - CheckHistoryText(_history.GetPrevious("2"), "2a"); // Skip over non-matching entry. - CheckHistoryText(_history.GetPrevious("2"), null); - } - - [WpfFact] - public void TestNextWithPattern_NoMatch() - { - AddEntries("start", "1", "12", "123"); - - CheckHistoryText(_history.GetPrevious(null), "123"); - CheckHistoryText(_history.GetPrevious(null), "12"); - CheckHistoryText(_history.GetPrevious(null), "1"); - CheckHistoryText(_history.GetPrevious(null), "start"); - - CheckHistoryText(_history.GetNext("4"), null); - CheckHistoryText(_history.GetNext("4"), null); - } - - [WpfFact] - public void TestNextWithPattern_PatternMaintained() - { - AddEntries("start", "1", "12", "123"); - - CheckHistoryText(_history.GetPrevious(null), "123"); - CheckHistoryText(_history.GetPrevious(null), "12"); - CheckHistoryText(_history.GetPrevious(null), "1"); - CheckHistoryText(_history.GetPrevious(null), "start"); - - CheckHistoryText(_history.GetNext("12"), "12"); // Skip over non-matching entry. - CheckHistoryText(_history.GetNext("12"), "123"); - CheckHistoryText(_history.GetNext("12"), null); - } - - [WpfFact] - public void TestNextWithPattern_PatternDropped() - { - AddEntries("start", "3", "2", "1"); - - CheckHistoryText(_history.GetPrevious(null), "1"); - CheckHistoryText(_history.GetPrevious(null), "2"); - CheckHistoryText(_history.GetPrevious(null), "3"); - CheckHistoryText(_history.GetPrevious(null), "start"); - - CheckHistoryText(_history.GetNext("2"), "2"); // Skip over non-matching entry. - CheckHistoryText(_history.GetNext(null), "1"); // Pattern isn't passed, so return to normal iteration. - CheckHistoryText(_history.GetNext(null), null); - } - - [WpfFact] - public void TestNextWithPattern_PatternChanged() - { - AddEntries("start", "2b", "1b", "2a", "1a"); - - CheckHistoryText(_history.GetPrevious(null), "1a"); - CheckHistoryText(_history.GetPrevious(null), "2a"); - CheckHistoryText(_history.GetPrevious(null), "1b"); - CheckHistoryText(_history.GetPrevious(null), "2b"); - CheckHistoryText(_history.GetPrevious(null), "start"); - - CheckHistoryText(_history.GetNext("1"), "1b"); // Skip over non-matching entry. - CheckHistoryText(_history.GetNext("2"), "2a"); // Skip over non-matching entry. - CheckHistoryText(_history.GetNext("2"), null); - } - - private void AddEntries(params string[] entries) - { - var oldLength = BufferLength; - - foreach (var entry in entries) - { - AddEntry(entry); - } - - Assert.Equal(string.Join(Environment.NewLine, entries) + Environment.NewLine, _buffer.CurrentSnapshot.GetText().Substring(oldLength)); - } - - private void AddEntry(string entry) - { - var oldLength = BufferLength; - var snapshot = _buffer.Insert(oldLength, entry); - var snapshotSpan = new SnapshotSpan(snapshot, new Span(oldLength, entry.Length)); - _history.Add(snapshotSpan); - _buffer.Insert(snapshot.Length, Environment.NewLine); - } - - private int BufferLength => _buffer.CurrentSnapshot.Length; - - private IEnumerable HistoryEntries => GetHistoryEntries(_history); - - private static IEnumerable GetHistoryEntries(History history) - { - return history.Items.Select(e => e.Text); - } - - private void CheckHistoryText(History.Entry actualEntry, string expectedText) - { - Assert.Equal(expectedText, actualEntry?.Text); - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/EditorTest/InteractiveClipboardFormatTests.cs b/src/InteractiveWindow/EditorTest/InteractiveClipboardFormatTests.cs deleted file mode 100644 index f7512b3737b9e..0000000000000 --- a/src/InteractiveWindow/EditorTest/InteractiveClipboardFormatTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Xunit; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public class InteractiveClipboardFormatTests - { - [Fact] - public void Deserialize_Errors() - { - Assert.Throws(() => InteractiveClipboardFormat.Deserialize(null)); - Assert.Throws(() => InteractiveClipboardFormat.Deserialize(1)); - Assert.Throws(() => InteractiveClipboardFormat.Deserialize("foo")); - - Assert.Throws(() => InteractiveClipboardFormat.Deserialize(@" -[ - {""content"":""A"",""kind"":1}, - {""content"":""B"",""kind"":1000000000000000000000}, - {""content"":""C"",""kind"":1}, -]")); - - Assert.Throws(() => InteractiveClipboardFormat.Deserialize(@" -[ - {""content"":""A"",""kind"":1}, - {""content"":""B"",""kind"":""x""}, - {""content"":""C"",""kind"":1}, -]")); - } - - [Fact] - public void Deserialize() - { - var serialized = BufferBlock.Serialize(new[] - { - new BufferBlock(ReplSpanKind.Input, "I"), - new BufferBlock(ReplSpanKind.Output, "O"), - new BufferBlock(ReplSpanKind.LineBreak, "LB"), - new BufferBlock(ReplSpanKind.Prompt, "P"), - new BufferBlock(ReplSpanKind.StandardInput, "SI"), - }); - - Assert.Equal("IOLBSI", InteractiveClipboardFormat.Deserialize(serialized)); - - // missing kind interpreted as Prompt, which is ignored: - Assert.Equal("AC", InteractiveClipboardFormat.Deserialize(@" -[ - {""content"":""A"",""kind"":1}, - {""content"":""B"",""x"":1}, - {""content"":""C"",""kind"":1}, -]")); - - // invalid kind ignored: - Assert.Equal("AC", InteractiveClipboardFormat.Deserialize(@" -[ - {""content"":""A"",""kind"":1}, - {""content"":""B"",""kind"":-1}, - {""content"":""C"",""kind"":1}, -]")); - - // invalid kind ignored: - Assert.Equal("AC", InteractiveClipboardFormat.Deserialize(@" -[ - {""content"":""A"",""kind"":1}, - {""content"":""B"",""kind"":-1}, - {""content"":""C"",""kind"":1}, -]")); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/InteractiveWindowEditorsFactoryService.cs b/src/InteractiveWindow/EditorTest/InteractiveWindowEditorsFactoryService.cs deleted file mode 100644 index f8042ee07e765..0000000000000 --- a/src/InteractiveWindow/EditorTest/InteractiveWindowEditorsFactoryService.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; -using Roslyn.Test.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - [Export(typeof(IInteractiveWindowEditorFactoryService))] - internal class InteractiveWindowEditorsFactoryService : IInteractiveWindowEditorFactoryService - { - public const string ContentType = "text"; - - private readonly ITextBufferFactoryService _textBufferFactoryService; - private readonly ITextEditorFactoryService _textEditorFactoryService; - private readonly IContentTypeRegistryService _contentTypeRegistry; - - [ImportingConstructor] - public InteractiveWindowEditorsFactoryService(ITextBufferFactoryService textBufferFactoryService, ITextEditorFactoryService textEditorFactoryService, IContentTypeRegistryService contentTypeRegistry) - { - _textBufferFactoryService = textBufferFactoryService; - _textEditorFactoryService = textEditorFactoryService; - _contentTypeRegistry = contentTypeRegistry; - } - - IWpfTextView IInteractiveWindowEditorFactoryService.CreateTextView(IInteractiveWindow window, ITextBuffer buffer, ITextViewRoleSet roles) - { - WpfTestCase.RequireWpfFact($"Creates an IWpfTextView in {nameof(InteractiveWindowEditorsFactoryService)}"); - - var textView = _textEditorFactoryService.CreateTextView(buffer, roles); - return _textEditorFactoryService.CreateTextViewHost(textView, false).TextView; - } - - ITextBuffer IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(IInteractiveWindow window) - { - IContentType contentType; - if (!window.Properties.TryGetProperty(typeof(IContentType), out contentType)) - { - contentType = _contentTypeRegistry.GetContentType(ContentType); - } - - return _textBufferFactoryService.CreateTextBuffer(contentType); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/InteractiveWindowHistoryTests.cs b/src/InteractiveWindow/EditorTest/InteractiveWindowHistoryTests.cs deleted file mode 100644 index 226aaa5100763..0000000000000 --- a/src/InteractiveWindow/EditorTest/InteractiveWindowHistoryTests.cs +++ /dev/null @@ -1,560 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Text; -using Xunit; -using Roslyn.Test.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public class InteractiveWindowHistoryTests : IDisposable - { - #region Helpers - - private readonly InteractiveWindowTestHost _testHost; - private readonly IInteractiveWindow _window; - private readonly IInteractiveWindowOperations _operations; - - public InteractiveWindowHistoryTests() - { - _testHost = new InteractiveWindowTestHost(); - _window = _testHost.Window; - _operations = _window.Operations; - } - - void IDisposable.Dispose() - { - _testHost.Dispose(); - } - - /// - /// Sets the active code to the specified text w/o executing it. - /// - private void SetActiveCode(string text) - { - using (var edit = _window.CurrentLanguageBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, editTag: null)) - { - edit.Replace(new Span(0, _window.CurrentLanguageBuffer.CurrentSnapshot.Length), text); - edit.Apply(); - } - } - - private async Task InsertAndExecuteInputs(params string[] inputs) - { - foreach (var input in inputs) - { - await InsertAndExecuteInput(input).ConfigureAwait(true); - } - } - - private async Task InsertAndExecuteInput(string input) - { - _window.InsertCode(input); - AssertCurrentSubmission(input); - await ExecuteInput().ConfigureAwait(true); - } - - private async Task ExecuteInput() - { - await ((InteractiveWindow)_window).ExecuteInputAsync().ConfigureAwait(true); - } - - private void AssertCurrentSubmission(string expected) - { - Assert.Equal(expected, _window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); - } - - #endregion Helpers - - [WpfFact] - public async Task CheckHistoryPrevious() - { - const string inputString = "1 "; - await InsertAndExecuteInput(inputString).ConfigureAwait(true); - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString); - } - - [WpfFact] - public async Task CheckHistoryPreviousWithAnEmptySubmission() { - //submit, submit, submit, up, up, up - const string inputString1 = "1 "; - const string inputString2 = " "; - const string inputString3 = "3 "; - - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - await InsertAndExecuteInput(inputString3).ConfigureAwait(true); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString3); - - //second input was empty, so it wasn't added to history - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - - //has reached the top, no change - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - } - - [WpfFact] - public async Task CheckHistoryPreviousNotCircular() - { - //submit, submit, up, up, up - const string inputString1 = "1 "; - const string inputString2 = "2 "; - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - //this up should not be circular - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - } - - [WpfFact] - public async Task CheckHistoryPreviousAfterSubmittingEntryFromHistory() - { - //submit, submit, submit, up, up, submit, up, up, up - const string inputString1 = "1 "; - const string inputString2 = "2 "; - const string inputString3 = "3 "; - - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - await InsertAndExecuteInput(inputString3).ConfigureAwait(true); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString3); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - - await ExecuteInput().ConfigureAwait(true); - - //history navigation should start from the last history pointer - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - - //has reached the top, no change - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - } - - [WpfFact] - public async Task CheckHistoryPreviousAfterSubmittingNewEntryWhileNavigatingHistory() - { - //submit, submit, up, up, submit new, up, up, up - const string inputString1 = "1 "; - const string inputString2 = "2 "; - const string inputString3 = "3 "; - - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - - SetActiveCode(inputString3); - AssertCurrentSubmission(inputString3); - await ExecuteInput().ConfigureAwait(true); - - //History pointer should be reset. Previous should now bring up last entry - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString3); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - - //has reached the top, no change - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - } - - [WpfFact] - public async Task CheckHistoryNextNotCircular() - { - //submit, submit, down, up, down, down - const string inputString1 = "1 "; - const string inputString2 = "2 "; - const string empty = ""; - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - - //Next should do nothing as history pointer is uninitialized and there is - //no next entry. Buffer should be empty - _operations.HistoryNext(); - AssertCurrentSubmission(empty); - - //Go back once entry - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - - //Go fwd one entry - should do nothing as history pointer is at last entry - //buffer should have same value as before - _operations.HistoryNext(); - AssertCurrentSubmission(inputString2); - - //Next should again do nothing as it is the last item, buffer should have the same value - _operations.HistoryNext(); - AssertCurrentSubmission(inputString2); - - //This is to make sure the window doesn't crash - await ExecuteInput().ConfigureAwait(true); - AssertCurrentSubmission(empty); - } - - [WpfFact] - public async Task CheckHistoryNextAfterSubmittingEntryFromHistory() - { - //submit, submit, submit, up, up, submit, down, down, down - const string inputString1 = "1 "; - const string inputString2 = "2 "; - const string inputString3 = "3 "; - - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - await InsertAndExecuteInput(inputString3).ConfigureAwait(true); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString3); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - - //submit inputString2 again. Should be added at the end of history - await ExecuteInput().ConfigureAwait(true); - - //history navigation should start from the last history pointer - _operations.HistoryNext(); - AssertCurrentSubmission(inputString3); - - //This next should take us to the InputString2 which was resubmitted - _operations.HistoryNext(); - AssertCurrentSubmission(inputString2); - - //has reached the top, no change - _operations.HistoryNext(); - AssertCurrentSubmission(inputString2); - } - - [WpfFact] - public async Task CheckHistoryNextAfterSubmittingNewEntryWhileNavigatingHistory() - { - //submit, submit, up, up, submit new, down, up - const string inputString1 = "1 "; - const string inputString2 = "2 "; - const string inputString3 = "3 "; - const string empty = ""; - - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString2); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString1); - - SetActiveCode(inputString3); - AssertCurrentSubmission(inputString3); - await ExecuteInput().ConfigureAwait(true); - - //History pointer should be reset. next should do nothing - _operations.HistoryNext(); - AssertCurrentSubmission(empty); - - _operations.HistoryPrevious(); - AssertCurrentSubmission(inputString3); - } - - [WpfFact] - public async Task CheckUncommittedInputAfterNavigatingHistory() - { - //submit, submit, up, up, submit new, down, up - const string inputString1 = "1 "; - const string inputString2 = "2 "; - const string uncommittedInput = nameof(uncommittedInput); - - await InsertAndExecuteInput(inputString1).ConfigureAwait(true); - await InsertAndExecuteInput(inputString2).ConfigureAwait(true); - //Add uncommitted input - SetActiveCode(uncommittedInput); - //Navigate history. This should save uncommitted input - _operations.HistoryPrevious(); - //Navigate to next item at the end of history. - //This should bring back uncommitted input - _operations.HistoryNext(); - AssertCurrentSubmission(uncommittedInput); - } - - [WpfFact] - public async Task CheckHistoryPreviousAfterReset() - { - const string resetCommand1 = "#reset"; - const string resetCommand2 = "#reset "; - await InsertAndExecuteInput(resetCommand1).ConfigureAwait(true); - await InsertAndExecuteInput(resetCommand2).ConfigureAwait(true); - _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand2); - _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1); - _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1); - } - - [WpfFact] - public async Task TestHistoryPrevious() - { - await InsertAndExecuteInputs("1", "2", "3").ConfigureAwait(true); - - _operations.HistoryPrevious(); AssertCurrentSubmission("3"); - _operations.HistoryPrevious(); AssertCurrentSubmission("2"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - } - - [WpfFact] - public async Task TestHistoryNext() - { - await InsertAndExecuteInputs("1", "2", "3").ConfigureAwait(true); - - SetActiveCode("4"); - - _operations.HistoryNext(); AssertCurrentSubmission("4"); - _operations.HistoryNext(); AssertCurrentSubmission("4"); - _operations.HistoryPrevious(); AssertCurrentSubmission("3"); - _operations.HistoryPrevious(); AssertCurrentSubmission("2"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryNext(); AssertCurrentSubmission("2"); - _operations.HistoryNext(); AssertCurrentSubmission("3"); - _operations.HistoryNext(); AssertCurrentSubmission("4"); - _operations.HistoryNext(); AssertCurrentSubmission("4"); - } - - [WpfFact] - public async Task TestHistoryPreviousWithPattern_NoMatch() - { - await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true); - - _operations.HistoryPrevious("4"); AssertCurrentSubmission(""); - _operations.HistoryPrevious("4"); AssertCurrentSubmission(""); - } - - [WpfFact] - public async Task TestHistoryPreviousWithPattern_PatternMaintained() - { - await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true); - - _operations.HistoryPrevious("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry. - _operations.HistoryPrevious("12"); AssertCurrentSubmission("123"); - _operations.HistoryPrevious("12"); AssertCurrentSubmission("123"); - } - - [WpfFact] - public async Task TestHistoryPreviousWithPattern_PatternDropped() - { - await InsertAndExecuteInputs("1", "2", "3").ConfigureAwait(true); - - _operations.HistoryPrevious("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry. - _operations.HistoryPrevious(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration. - _operations.HistoryPrevious(null); AssertCurrentSubmission("1"); - } - - [WpfFact] - public async Task TestHistoryPreviousWithPattern_PatternChanged() - { - await InsertAndExecuteInputs("10", "20", "15", "25").ConfigureAwait(true); - - _operations.HistoryPrevious("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry. - _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry. - _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); - } - - [WpfFact] - public async Task TestHistoryNextWithPattern_NoMatch() - { - await InsertAndExecuteInputs("start", "1", "12", "123").ConfigureAwait(true); - SetActiveCode("end"); - - _operations.HistoryPrevious(); AssertCurrentSubmission("123"); - _operations.HistoryPrevious(); AssertCurrentSubmission("12"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryPrevious(); AssertCurrentSubmission("start"); - - _operations.HistoryNext("4"); AssertCurrentSubmission("end"); - _operations.HistoryNext("4"); AssertCurrentSubmission("end"); - } - - [WpfFact] - public async Task TestHistoryNextWithPattern_PatternMaintained() - { - await InsertAndExecuteInputs("start", "1", "12", "123").ConfigureAwait(true); - SetActiveCode("end"); - - _operations.HistoryPrevious(); AssertCurrentSubmission("123"); - _operations.HistoryPrevious(); AssertCurrentSubmission("12"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryPrevious(); AssertCurrentSubmission("start"); - - _operations.HistoryNext("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry. - _operations.HistoryNext("12"); AssertCurrentSubmission("123"); - _operations.HistoryNext("12"); AssertCurrentSubmission("end"); - } - - [WpfFact] - public async Task TestHistoryNextWithPattern_PatternDropped() - { - await InsertAndExecuteInputs("start", "3", "2", "1").ConfigureAwait(true); - SetActiveCode("end"); - - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryPrevious(); AssertCurrentSubmission("2"); - _operations.HistoryPrevious(); AssertCurrentSubmission("3"); - _operations.HistoryPrevious(); AssertCurrentSubmission("start"); - - _operations.HistoryNext("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry. - _operations.HistoryNext(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration. - _operations.HistoryNext(null); AssertCurrentSubmission("end"); - } - - [WpfFact] - public async Task TestHistoryNextWithPattern_PatternChanged() - { - await InsertAndExecuteInputs("start", "25", "15", "20", "10").ConfigureAwait(true); - SetActiveCode("end"); - - _operations.HistoryPrevious(); AssertCurrentSubmission("10"); - _operations.HistoryPrevious(); AssertCurrentSubmission("20"); - _operations.HistoryPrevious(); AssertCurrentSubmission("15"); - _operations.HistoryPrevious(); AssertCurrentSubmission("25"); - _operations.HistoryPrevious(); AssertCurrentSubmission("start"); - - _operations.HistoryNext("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry. - _operations.HistoryNext("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry. - _operations.HistoryNext("2"); AssertCurrentSubmission("end"); - } - - [WpfFact] - public async Task TestHistorySearchPrevious() - { - await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true); - - // Default search string is empty. - _operations.HistorySearchPrevious(); AssertCurrentSubmission("1"); // Pattern is captured before this step. - _operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); - _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); - _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); - } - - [WpfFact] - public async Task TestHistorySearchPreviousWithPattern() - { - await InsertAndExecuteInputs("123", "12", "1").ConfigureAwait(true); - SetActiveCode("12"); - - _operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); // Pattern is captured before this step. - _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); - _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); - } - - [WpfFact] - public async Task TestHistorySearchNextWithPattern() - { - await InsertAndExecuteInputs("12", "123", "12", "1").ConfigureAwait(true); - SetActiveCode("end"); - - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistoryPrevious(); AssertCurrentSubmission("12"); - _operations.HistoryPrevious(); AssertCurrentSubmission("123"); - _operations.HistoryPrevious(); AssertCurrentSubmission("12"); - - _operations.HistorySearchNext(); AssertCurrentSubmission("123"); // Pattern is captured before this step. - _operations.HistorySearchNext(); AssertCurrentSubmission("12"); - _operations.HistorySearchNext(); AssertCurrentSubmission("end"); - } - - [WpfFact] - public async Task TestHistoryPreviousAndSearchPrevious() - { - await InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1").ConfigureAwait(true); - - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step. - _operations.HistoryPrevious(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. - _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. - _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); - _operations.HistoryPrevious(); AssertCurrentSubmission("200"); - _operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious. - } - - [WpfFact] - public async Task TestHistoryPreviousAndSearchPrevious_ExplicitPattern() - { - await InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1").ConfigureAwait(true); - - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - _operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step. - _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. - _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. - _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); - _operations.HistoryPrevious("2"); AssertCurrentSubmission("200"); - _operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious. - } - - [WpfFact] - public async Task TestHistoryNextAndSearchNext() - { - await InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200").ConfigureAwait(true); - SetActiveCode("4"); - - _operations.HistoryPrevious(); AssertCurrentSubmission("200"); - _operations.HistoryPrevious(); AssertCurrentSubmission("100"); - _operations.HistoryPrevious(); AssertCurrentSubmission("30"); - _operations.HistoryPrevious(); AssertCurrentSubmission("20"); - _operations.HistoryPrevious(); AssertCurrentSubmission("10"); - _operations.HistoryPrevious(); AssertCurrentSubmission("2"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - - _operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step. - _operations.HistoryNext(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. - _operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. - _operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext. - _operations.HistoryNext(); AssertCurrentSubmission("4"); - } - - [WpfFact] - public async Task TestHistoryNextAndSearchNext_ExplicitPattern() - { - await InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200").ConfigureAwait(true); - SetActiveCode("4"); - - _operations.HistoryPrevious(); AssertCurrentSubmission("200"); - _operations.HistoryPrevious(); AssertCurrentSubmission("100"); - _operations.HistoryPrevious(); AssertCurrentSubmission("30"); - _operations.HistoryPrevious(); AssertCurrentSubmission("20"); - _operations.HistoryPrevious(); AssertCurrentSubmission("10"); - _operations.HistoryPrevious(); AssertCurrentSubmission("2"); - _operations.HistoryPrevious(); AssertCurrentSubmission("1"); - - _operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step. - _operations.HistoryNext("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. - _operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. - _operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext. - _operations.HistoryNext("2"); AssertCurrentSubmission("4"); - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/EditorTest/InteractiveWindowTest.csproj b/src/InteractiveWindow/EditorTest/InteractiveWindowTest.csproj deleted file mode 100644 index 20defc83811b1..0000000000000 --- a/src/InteractiveWindow/EditorTest/InteractiveWindowTest.csproj +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - true - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3} - Library - Microsoft.VisualStudio.InteractiveWindow.UnitTests - Microsoft.VisualStudio.InteractiveWindow.UnitTests - v4.6 - - - - - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - - - - - - diff --git a/src/InteractiveWindow/EditorTest/InteractiveWindowTestHost.cs b/src/InteractiveWindow/EditorTest/InteractiveWindowTestHost.cs deleted file mode 100644 index 6adc14f9e50cc..0000000000000 --- a/src/InteractiveWindow/EditorTest/InteractiveWindowTestHost.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.ComponentModel.Composition.Hosting; -using System.Linq; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public sealed class InteractiveWindowTestHost : IDisposable - { - internal readonly IInteractiveWindow Window; - internal readonly CompositionContainer ExportProvider; - internal readonly TestInteractiveEngine Evaluator; - - private static readonly Lazy s_lazyCatalog = new Lazy(() => - { - var types = new[] { typeof(TestInteractiveEngine), typeof(InteractiveWindow) }.Concat(GetVisualStudioTypes()); - return new AggregateCatalog(types.Select(t => new AssemblyCatalog(t.Assembly))); - }); - - internal InteractiveWindowTestHost(Action stateChangedHandler = null) - { - ExportProvider = new CompositionContainer( - s_lazyCatalog.Value, - CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe); - - var contentTypeRegistryService = ExportProvider.GetExport().Value; - Evaluator = new TestInteractiveEngine(contentTypeRegistryService); - Window = ExportProvider.GetExport().Value.CreateWindow(Evaluator); - ((InteractiveWindow)Window).StateChanged += stateChangedHandler; - Window.InitializeAsync().Wait(); - } - - public static Type[] GetVisualStudioTypes() - { - var types = new[] - { - // EDITOR - - // Microsoft.VisualStudio.Platform.VSEditor.dll: - typeof(Microsoft.VisualStudio.Platform.VSEditor.EventArgsHelper), - - // Microsoft.VisualStudio.Text.Logic.dll: - // Must include this because several editor options are actually stored as exported information - // on this DLL. Including most importantly, the tab size information. - typeof(Microsoft.VisualStudio.Text.Editor.DefaultOptions), - - // Microsoft.VisualStudio.Text.UI.dll: - // Include this DLL to get several more EditorOptions including WordWrapStyle. - typeof(Microsoft.VisualStudio.Text.Editor.WordWrapStyle), - - // Microsoft.VisualStudio.Text.UI.Wpf.dll: - // Include this DLL to get more EditorOptions values. - typeof(Microsoft.VisualStudio.Text.Editor.HighlightCurrentLineOption), - - // BasicUndo.dll: - // Include this DLL to satisfy ITextUndoHistoryRegistry - typeof(BasicUndo.IBasicUndoHistory), - - // Microsoft.VisualStudio.Language.StandardClassification.dll: - typeof(Microsoft.VisualStudio.Language.StandardClassification.PredefinedClassificationTypeNames) - }; - - return types; - } - - public void Dispose() - { - if (Window != null) - { - // close interactive host process: - var engine = Window.Evaluator; - if (engine != null) - { - engine.Dispose(); - } - - // dispose buffer: - Window.Dispose(); - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/InteractiveWindowTests.cs b/src/InteractiveWindow/EditorTest/InteractiveWindowTests.cs deleted file mode 100644 index 140425912581a..0000000000000 --- a/src/InteractiveWindow/EditorTest/InteractiveWindowTests.cs +++ /dev/null @@ -1,1482 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; -using Microsoft.VisualStudio.InteractiveWindow.Commands; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Projection; -using Microsoft.VisualStudio.Utilities; -using Moq; -using Xunit; -using Roslyn.Test.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public partial class InteractiveWindowTests : IDisposable - { - #region Helpers - - private InteractiveWindowTestHost _testHost; - private List _states; - private readonly TestClipboard _testClipboard; - private readonly TaskFactory _factory = new TaskFactory(TaskScheduler.Default); - - public InteractiveWindowTests() - { - _states = new List(); - _testHost = new InteractiveWindowTestHost(_states.Add); - _testClipboard = new TestClipboard(); - ((InteractiveWindow)Window).InteractiveWindowClipboard = _testClipboard; - } - - void IDisposable.Dispose() - { - _testHost.Dispose(); - } - - private IInteractiveWindow Window => _testHost.Window; - - private Task TaskRun(Action action) - { - return _factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); - } - - private static IEnumerable MockCommands(params string[] commandNames) - { - foreach (var name in commandNames) - { - var mock = new Mock(); - mock.Setup(m => m.Names).Returns(new[] { name }); - mock.Setup(m => m.Description).Returns(string.Format("Description of {0} command.", name)); - yield return mock.Object; - } - } - - private static ITextSnapshot MockSnapshot(string content) - { - var snapshotMock = new Mock(); - snapshotMock.Setup(m => m[It.IsAny()]).Returns(index => content[index]); - snapshotMock.Setup(m => m.Length).Returns(content.Length); - snapshotMock.Setup(m => m.GetText()).Returns(content); - snapshotMock.Setup(m => m.GetText(It.IsAny(), It.IsAny())).Returns((start, length) => content.Substring(start, length)); - snapshotMock.Setup(m => m.GetText(It.IsAny())).Returns(span => content.Substring(span.Start, span.Length)); - return snapshotMock.Object; - } - - #endregion - - [WpfFact] - public void InteractiveWindow__CommandParsing() - { - var commandList = MockCommands("foo", "bar", "bz", "command1").ToArray(); - var commands = new Commands.Commands(null, "%", commandList); - AssertEx.Equal(commands.GetCommands(), commandList); - - var cmdBar = commandList[1]; - Assert.Equal("bar", cmdBar.Names.First()); - - Assert.Equal("%", commands.CommandPrefix); - commands.CommandPrefix = "#"; - Assert.Equal("#", commands.CommandPrefix); - - //// 111111 - //// 0123456789012345 - var s1 = MockSnapshot("#bar arg1 arg2 "); - - SnapshotSpan prefixSpan, commandSpan, argsSpan; - IInteractiveWindowCommand cmd; - - cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 0)), out prefixSpan, out commandSpan, out argsSpan); - Assert.Null(cmd); - - cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 1)), out prefixSpan, out commandSpan, out argsSpan); - Assert.Null(cmd); - - cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 2)), out prefixSpan, out commandSpan, out argsSpan); - Assert.Null(cmd); - Assert.Equal(0, prefixSpan.Start); - Assert.Equal(1, prefixSpan.End); - Assert.Equal(1, commandSpan.Start); - Assert.Equal(2, commandSpan.End); - Assert.Equal(2, argsSpan.Start); - Assert.Equal(2, argsSpan.End); - - cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 3)), out prefixSpan, out commandSpan, out argsSpan); - Assert.Null(cmd); - Assert.Equal(0, prefixSpan.Start); - Assert.Equal(1, prefixSpan.End); - Assert.Equal(1, commandSpan.Start); - Assert.Equal(3, commandSpan.End); - Assert.Equal(3, argsSpan.Start); - Assert.Equal(3, argsSpan.End); - - cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 4)), out prefixSpan, out commandSpan, out argsSpan); - Assert.Equal(cmdBar, cmd); - Assert.Equal(0, prefixSpan.Start); - Assert.Equal(1, prefixSpan.End); - Assert.Equal(1, commandSpan.Start); - Assert.Equal(4, commandSpan.End); - Assert.Equal(4, argsSpan.Start); - Assert.Equal(4, argsSpan.End); - - cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 5)), out prefixSpan, out commandSpan, out argsSpan); - Assert.Equal(cmdBar, cmd); - Assert.Equal(0, prefixSpan.Start); - Assert.Equal(1, prefixSpan.End); - Assert.Equal(1, commandSpan.Start); - Assert.Equal(4, commandSpan.End); - Assert.Equal(5, argsSpan.Start); - Assert.Equal(5, argsSpan.End); - - cmd = commands.TryParseCommand(s1.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); - Assert.Equal(cmdBar, cmd); - Assert.Equal(0, prefixSpan.Start); - Assert.Equal(1, prefixSpan.End); - Assert.Equal(1, commandSpan.Start); - Assert.Equal(4, commandSpan.End); - Assert.Equal(5, argsSpan.Start); - Assert.Equal(14, argsSpan.End); - - //// - //// 0123456789 - var s2 = MockSnapshot(" #bar "); - cmd = commands.TryParseCommand(s2.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); - Assert.Equal(cmdBar, cmd); - Assert.Equal(2, prefixSpan.Start); - Assert.Equal(3, prefixSpan.End); - Assert.Equal(3, commandSpan.Start); - Assert.Equal(6, commandSpan.End); - Assert.Equal(9, argsSpan.Start); - Assert.Equal(9, argsSpan.End); - - //// 111111 - //// 0123456789012345 - var s3 = MockSnapshot(" # bar args"); - cmd = commands.TryParseCommand(s3.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); - Assert.Equal(cmdBar, cmd); - Assert.Equal(2, prefixSpan.Start); - Assert.Equal(3, prefixSpan.End); - Assert.Equal(6, commandSpan.Start); - Assert.Equal(9, commandSpan.End); - Assert.Equal(11, argsSpan.Start); - Assert.Equal(15, argsSpan.End); - } - - [WpfFact] - public void InteractiveWindow_GetCommands() - { - var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands( - Window, - "#", - _testHost.ExportProvider.GetExports().Select(x => x.Value).ToArray()); - - var commands = interactiveCommands.GetCommands(); - - Assert.NotEmpty(commands); - Assert.Equal(2, commands.Where(n => n.Names.First() == "cls").Count()); - Assert.Equal(2, commands.Where(n => n.Names.Last() == "clear").Count()); - Assert.NotNull(commands.Where(n => n.Names.First() == "help").SingleOrDefault()); - Assert.NotNull(commands.Where(n => n.Names.First() == "reset").SingleOrDefault()); - } - - [WorkItem(8121, "https://github.com/dotnet/roslyn/issues/8121")] - [WpfFact] - public void InteractiveWindow_GetHelpShortcutDescriptionss() - { - var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands( - Window, - string.Empty, - Enumerable.Empty()); - - var noSmartUpDownExpected = -@" Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. - Ctrl-Enter Within the current submission, evaluate the current submission. - Within a previous submission, append the previous submission to the current submission. - Shift-Enter Insert a new line. - Escape Clear the current submission. - Alt-UpArrow Replace the current submission with a previous submission. - Alt-DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). - Ctrl-Alt-UpArrow Replace the current submission with a previous submission beginning with the same text. - Ctrl-Alt-DownArrow Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards). - Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input. - Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer. - Ctrl-A First press, select the submission containing the cursor. Second press, select all text in the window. -"; - - // By default, SmartUpDown option is not set - var descriptions = ((Commands.Commands)interactiveCommands).ShortcutDescriptions; - Assert.Equal(noSmartUpDownExpected, descriptions); - - - var withSmartUpDownExpected = -@" Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. - Ctrl-Enter Within the current submission, evaluate the current submission. - Within a previous submission, append the previous submission to the current submission. - Shift-Enter Insert a new line. - Escape Clear the current submission. - Alt-UpArrow Replace the current submission with a previous submission. - Alt-DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). - Ctrl-Alt-UpArrow Replace the current submission with a previous submission beginning with the same text. - Ctrl-Alt-DownArrow Replace the current submission with a subsequent submission beginning with the same text (after having previously navigated backwards). - Ctrl-K, Ctrl-Enter Paste the selection at the end of interactive buffer, leave caret at the end of input. - Ctrl-E, Ctrl-Enter Paste and execute the selection before any pending input in the interactive buffer. - Ctrl-A First press, select the submission containing the cursor. Second press, select all text in the window. - UpArrow At the end of the current submission, replace the current submission with a previous submission. - Elsewhere, move the cursor up one line. - DownArrow At the end of the current submission, replace the current submission with a subsequent submission (after having previously navigated backwards). - Elsewhere, move the cursor down one line. -"; - - // Set SmartUpDown option to true - Window.TextView.Options.SetOptionValue(InteractiveWindowOptions.SmartUpDown, true); - - descriptions = ((Commands.Commands)interactiveCommands).ShortcutDescriptions; - Assert.Equal(withSmartUpDownExpected, descriptions); - } - - [WorkItem(6625, "https://github.com/dotnet/roslyn/issues/6625")] - [WpfFact] - public void InteractiveWindow_DisplayCommandsHelp() - { - var commandList = MockCommands("foo").ToArray(); - var commands = new Commands.Commands(null, "&", commandList); - - Assert.Equal(new string[] { "&foo Description of foo command." }, commands.Help().ToArray()); - } - - [WorkItem(3970, "https://github.com/dotnet/roslyn/issues/3970")] - [WpfFact] - public async Task ResetStateTransitions() - { - await Window.Operations.ResetAsync().ConfigureAwait(true); - Assert.Equal(_states, new[] - { - InteractiveWindow.State.Initializing, - InteractiveWindow.State.WaitingForInput, - InteractiveWindow.State.Resetting, - InteractiveWindow.State.WaitingForInput, - }); - } - - [WpfFact] - public async Task DoubleInitialize() - { - try - { - await Window.InitializeAsync().ConfigureAwait(true); - Assert.True(false); - } - catch (InvalidOperationException) - { - } - } - - [WpfFact] - public void AccessPropertiesOnUIThread() - { - foreach (var property in typeof(IInteractiveWindow).GetProperties()) - { - Assert.Null(property.SetMethod); - property.GetMethod.Invoke(Window, Array.Empty()); - } - - Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties()); - } - - [WpfFact] - public async Task AccessPropertiesOnNonUIThread() - { - foreach (var property in typeof(IInteractiveWindow).GetProperties()) - { - Assert.Null(property.SetMethod); - await TaskRun(() => property.GetMethod.Invoke(Window, Array.Empty())).ConfigureAwait(true); - } - - Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties()); - } - - /// - /// Confirm that we are, in fact, running on a non-UI thread. - /// - [WpfFact] - public async Task NonUIThread() - { - await TaskRun(() => Assert.False(((InteractiveWindow)Window).OnUIThread())).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallCloseOnNonUIThread() - { - await TaskRun(() => Window.Close()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallInsertCodeOnNonUIThread() - { - await TaskRun(() => Window.InsertCode("1")).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallSubmitAsyncOnNonUIThread() - { - await TaskRun(() => Window.SubmitAsync(Array.Empty()).GetAwaiter().GetResult()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallWriteOnNonUIThread() - { - await TaskRun(() => Window.WriteLine("1")).ConfigureAwait(true); - await TaskRun(() => Window.Write("1")).ConfigureAwait(true); - await TaskRun(() => Window.WriteErrorLine("1")).ConfigureAwait(true); - await TaskRun(() => Window.WriteError("1")).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallFlushOutputOnNonUIThread() - { - Window.Write("1"); // Something to flush. - await TaskRun(() => Window.FlushOutput()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallAddInputOnNonUIThread() - { - await TaskRun(() => Window.AddInput("1")).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallAddToHistoryOnNonUIThread() - { - await TaskRun(() => Window.AddToHistory("1")).ConfigureAwait(true); - } - - /// - /// Call is blocking, so we can't write a simple non-failing test. - /// - [WpfFact] - public void CallReadStandardInputOnUIThread() - { - Assert.Throws(() => Window.ReadStandardInput()); - } - - [WpfFact] - public async Task CallBackspaceOnNonUIThread() - { - Window.InsertCode("1"); // Something to backspace. - await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallBreakLineOnNonUIThread() - { - await TaskRun(() => Window.Operations.BreakLine()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallClearHistoryOnNonUIThread() - { - Window.AddInput("1"); // Need a history entry. - await TaskRun(() => Window.Operations.ClearHistory()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallClearViewOnNonUIThread() - { - Window.InsertCode("1"); // Something to clear. - await TaskRun(() => Window.Operations.ClearView()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallHistoryNextOnNonUIThread() - { - Window.AddInput("1"); // Need a history entry. - await TaskRun(() => Window.Operations.HistoryNext()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallHistoryPreviousOnNonUIThread() - { - Window.AddInput("1"); // Need a history entry. - await TaskRun(() => Window.Operations.HistoryPrevious()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallHistorySearchNextOnNonUIThread() - { - Window.AddInput("1"); // Need a history entry. - await TaskRun(() => Window.Operations.HistorySearchNext()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallHistorySearchPreviousOnNonUIThread() - { - Window.AddInput("1"); // Need a history entry. - await TaskRun(() => Window.Operations.HistorySearchPrevious()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallHomeOnNonUIThread() - { - Window.Operations.BreakLine(); // Distinguish Home from End. - await TaskRun(() => Window.Operations.Home(true)).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallEndOnNonUIThread() - { - Window.Operations.BreakLine(); // Distinguish Home from End. - await TaskRun(() => Window.Operations.End(true)).ConfigureAwait(true); - } - - [WpfFact] - public void ScrollToCursorOnHomeAndEndOnNonUIThread() - { - Window.InsertCode(new string('1', 512)); // a long input string - - var textView = Window.TextView; - - Window.Operations.Home(false); - Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition, - textView.Caret.Position.Affinity)); - Window.Operations.End(false); - Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition, - textView.Caret.Position.Affinity)); - } - - [WpfFact] - public async Task CallSelectAllOnNonUIThread() - { - Window.InsertCode("1"); // Something to select. - await TaskRun(() => Window.Operations.SelectAll()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallPasteOnNonUIThread() - { - await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallCutOnNonUIThread() - { - await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallDeleteOnNonUIThread() - { - await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallReturnOnNonUIThread() - { - await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallTrySubmitStandardInputOnNonUIThread() - { - await TaskRun(() => Window.Operations.TrySubmitStandardInput()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallResetAsyncOnNonUIThread() - { - await TaskRun(() => Window.Operations.ResetAsync()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallExecuteInputOnNonUIThread() - { - await TaskRun(() => Window.Operations.ExecuteInput()).ConfigureAwait(true); - } - - [WpfFact] - public async Task CallCancelOnNonUIThread() - { - await TaskRun(() => Window.Operations.Cancel()).ConfigureAwait(true); - } - - [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] - [WpfFact] - public void TestIndentation1() - { - TestIndentation(indentSize: 1); - } - - [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] - [WpfFact] - public void TestIndentation2() - { - TestIndentation(indentSize: 2); - } - - [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] - [WpfFact] - public void TestIndentation3() - { - TestIndentation(indentSize: 3); - } - - [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] - [WpfFact] - public void TestIndentation4() - { - TestIndentation(indentSize: 4); - } - - private void TestIndentation(int indentSize) - { - const int promptWidth = 2; - - _testHost.ExportProvider.GetExport().Value.SmartIndent = new TestSmartIndent( - promptWidth, - promptWidth + indentSize, - promptWidth - ); - - AssertCaretVirtualPosition(0, promptWidth); - Window.InsertCode("{"); - AssertCaretVirtualPosition(0, promptWidth + 1); - Window.Operations.BreakLine(); - AssertCaretVirtualPosition(1, promptWidth + indentSize); - Window.InsertCode("Console.WriteLine();"); - Window.Operations.BreakLine(); - AssertCaretVirtualPosition(2, promptWidth); - Window.InsertCode("}"); - AssertCaretVirtualPosition(2, promptWidth + 1); - } - - private void AssertCaretVirtualPosition(int expectedLine, int expectedColumn) - { - ITextSnapshotLine actualLine; - int actualColumn; - Window.TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out actualLine, out actualColumn); - Assert.Equal(expectedLine, actualLine.LineNumber); - Assert.Equal(expectedColumn, actualColumn); - } - - [WpfFact] - public void ResetCommandArgumentParsing_Success() - { - bool initialize; - Assert.True(ResetCommand.TryParseArguments("", out initialize)); - Assert.True(initialize); - - Assert.True(ResetCommand.TryParseArguments(" ", out initialize)); - Assert.True(initialize); - - Assert.True(ResetCommand.TryParseArguments("\r\n", out initialize)); - Assert.True(initialize); - - Assert.True(ResetCommand.TryParseArguments("noconfig", out initialize)); - Assert.False(initialize); - - Assert.True(ResetCommand.TryParseArguments(" noconfig ", out initialize)); - Assert.False(initialize); - - Assert.True(ResetCommand.TryParseArguments("\r\nnoconfig\r\n", out initialize)); - Assert.False(initialize); - } - - [WpfFact] - public void ResetCommandArgumentParsing_Failure() - { - bool initialize; - Assert.False(ResetCommand.TryParseArguments("a", out initialize)); - Assert.False(ResetCommand.TryParseArguments("noconfi", out initialize)); - Assert.False(ResetCommand.TryParseArguments("noconfig1", out initialize)); - Assert.False(ResetCommand.TryParseArguments("noconfig 1", out initialize)); - Assert.False(ResetCommand.TryParseArguments("1 noconfig", out initialize)); - Assert.False(ResetCommand.TryParseArguments("noconfig\r\na", out initialize)); - Assert.False(ResetCommand.TryParseArguments("nOcOnfIg", out initialize)); - } - - [WpfFact] - public void ResetCommandNoConfigClassification() - { - Assert.Empty(ResetCommand.GetNoConfigPositions("")); - Assert.Empty(ResetCommand.GetNoConfigPositions("a")); - Assert.Empty(ResetCommand.GetNoConfigPositions("noconfi")); - Assert.Empty(ResetCommand.GetNoConfigPositions("noconfig1")); - Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig")); - Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig1")); - Assert.Empty(ResetCommand.GetNoConfigPositions("nOcOnfIg")); - - Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig")); - Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig ")); - Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig")); - Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig ")); - Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig")); - Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig\r\n")); - Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig\r\n")); - Assert.Equal(new[] { 6 }, ResetCommand.GetNoConfigPositions("error noconfig")); - - Assert.Equal(new[] { 0, 9 }, ResetCommand.GetNoConfigPositions("noconfig noconfig")); - Assert.Equal(new[] { 0, 15 }, ResetCommand.GetNoConfigPositions("noconfig error noconfig")); - } - - [WorkItem(4755, "https://github.com/dotnet/roslyn/issues/4755")] - [WpfFact] - public void ReformatBraces() - { - var buffer = Window.CurrentLanguageBuffer; - var snapshot = buffer.CurrentSnapshot; - Assert.Equal(0, snapshot.Length); - - // Text before reformatting. - snapshot = ApplyChanges( - buffer, - new TextChange(0, 0, "{ {\r\n } }")); - - // Text after reformatting. - Assert.Equal(9, snapshot.Length); - snapshot = ApplyChanges( - buffer, - new TextChange(1, 1, "\r\n "), - new TextChange(5, 1, " "), - new TextChange(7, 1, "\r\n")); - - // Text from language buffer. - var actualText = snapshot.GetText(); - Assert.Equal("{\r\n {\r\n }\r\n}", actualText); - - // Text including prompts. - buffer = Window.TextView.TextBuffer; - snapshot = buffer.CurrentSnapshot; - actualText = snapshot.GetText(); - Assert.Equal("> {\r\n> {\r\n> }\r\n> }", actualText); - - // Prompts should be read-only. - var regions = buffer.GetReadOnlyExtents(new Span(0, snapshot.Length)); - AssertEx.SetEqual(regions, - new Span(0, 2), - new Span(5, 2), - new Span(14, 2), - new Span(23, 2)); - } - - [WpfFact] - public async Task CancelMultiLineInput() - { - ApplyChanges( - Window.CurrentLanguageBuffer, - new TextChange(0, 0, "{\r\n {\r\n }\r\n}")); - - // Text including prompts. - var buffer = Window.TextView.TextBuffer; - var snapshot = buffer.CurrentSnapshot; - Assert.Equal("> {\r\n> {\r\n> }\r\n> }", snapshot.GetText()); - - await TaskRun(() => Window.Operations.Cancel()).ConfigureAwait(true); - - // Text after cancel. - snapshot = buffer.CurrentSnapshot; - Assert.Equal("> ", snapshot.GetText()); - } - - [WpfFact] - public void SelectAllInHeader() - { - Window.WriteLine("Header"); - Window.FlushOutput(); - var fullText = GetTextFromCurrentSnapshot(); - Assert.Equal("Header\r\n> ", fullText); - - Window.TextView.Caret.MoveTo(new SnapshotPoint(Window.TextView.TextBuffer.CurrentSnapshot, 1)); - Window.Operations.SelectAll(); // Used to throw. - - // Everything is selected. - Assert.Equal(new Span(0, fullText.Length), Window.TextView.Selection.SelectedSpans.Single().Span); - } - - [WpfFact] - public async Task DeleteWithOutSelectionInReadOnlyArea() - { - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - Window.InsertCode("2"); - - var caret = Window.TextView.Caret; - - // with empty selection, Delete() only handles caret movement, - // so we can only test caret location. - - // Delete() with caret in readonly area, no-op - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - AssertCaretVirtualPosition(1, 1); - - Window.Operations.Delete(); - AssertCaretVirtualPosition(1, 1); - - // Delete() with caret in active prompt, move caret to - // closest editable buffer - caret.MoveToNextCaretPosition(); - AssertCaretVirtualPosition(2, 0); - Window.Operations.Delete(); - AssertCaretVirtualPosition(2, 2); - } - - [WpfFact] - public async Task DeleteWithSelectionInReadonlyArea() - { - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - Window.InsertCode("23"); - - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - // Delete() with selection in readonly area, no-op - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - AssertCaretVirtualPosition(1, 1); - - Window.Operations.SelectAll(); - - Window.Operations.Delete(); - Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot()); - - // Delete() with selection in active prompt, no-op - selection.Clear(); - var start = caret.MoveToNextCaretPosition().VirtualBufferPosition; - caret.MoveToNextCaretPosition(); - var end = caret.MoveToNextCaretPosition().VirtualBufferPosition; - AssertCaretVirtualPosition(2, 2); - - selection.Select(start, end); - - Window.Operations.Delete(); - Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot()); - - // Delete() with selection overlaps with editable buffer, - // delete editable content and move caret to closest editable location - selection.Clear(); - caret.MoveToPreviousCaretPosition(); - start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition; - caret.MoveToNextCaretPosition(); - caret.MoveToNextCaretPosition(); - end = caret.MoveToNextCaretPosition().VirtualBufferPosition; - AssertCaretVirtualPosition(2, 3); - - selection.Select(start, end); - - Window.Operations.Delete(); - Assert.Equal("> 1\r\n1\r\n> 3", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(2, 2); - } - - [WpfFact] - public async Task BackspaceWithOutSelectionInReadOnlyArea() - { - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - Window.InsertCode("int x"); - Window.Operations.BreakLine(); - Window.InsertCode(";"); - - var caret = Window.TextView.Caret; - - // Backspace() with caret in readonly area, no-op - Window.Operations.Home(false); - Window.Operations.Home(false); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - Window.Operations.Home(false); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - AssertCaretVirtualPosition(1, 1); - - Window.Operations.Backspace(); - AssertCaretVirtualPosition(1, 1); - Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot()); - - // Backspace() with caret in 2nd active prompt, move caret to - // closest editable buffer then delete previous character (breakline) - caret.MoveToNextCaretPosition(); - Window.Operations.End(false); - caret.MoveToNextCaretPosition(); - caret.MoveToNextCaretPosition(); - AssertCaretVirtualPosition(3, 1); - - Window.Operations.Backspace(); - AssertCaretVirtualPosition(2, 7); - Assert.Equal("> 1\r\n1\r\n> int x;", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task BackspaceWithSelectionInReadonlyArea() - { - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - Window.InsertCode("int x"); - Window.Operations.BreakLine(); - Window.InsertCode(";"); - - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - // Backspace() with selection in readonly area, no-op - Window.Operations.Home(false); - Window.Operations.Home(false); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - Window.Operations.Home(false); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - AssertCaretVirtualPosition(1, 1); - - Window.Operations.SelectAll(); - - Window.Operations.Backspace(); - Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot()); - - // Backspace() with selection in active prompt, no-op - selection.Clear(); - var start = caret.MoveToNextCaretPosition().VirtualBufferPosition; - caret.MoveToNextCaretPosition(); - var end = caret.MoveToNextCaretPosition().VirtualBufferPosition; - AssertCaretVirtualPosition(2, 2); - - selection.Select(start, end); - - Window.Operations.Backspace(); - Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot()); - - // Backspace() with selection overlaps with editable buffer - selection.Clear(); - Window.Operations.End(false); - start = caret.Position.VirtualBufferPosition; - caret.MoveToNextCaretPosition(); - caret.MoveToNextCaretPosition(); - end = caret.MoveToNextCaretPosition().VirtualBufferPosition; - AssertCaretVirtualPosition(3, 2); - - selection.Select(start, end); - - Window.Operations.Backspace(); - Assert.Equal("> 1\r\n1\r\n> int x;", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(2, 7); - } - - [WpfFact] - public async Task ReturnWithOutSelectionInReadOnlyArea() - { - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - var caret = Window.TextView.Caret; - - // Return() with caret in readonly area, no-op - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - AssertCaretVirtualPosition(1, 1); - - Window.Operations.Return(); - AssertCaretVirtualPosition(1, 1); - - // Return() with caret in active prompt, move caret to - // closest editable buffer first - caret.MoveToNextCaretPosition(); - AssertCaretVirtualPosition(2, 0); - - Window.Operations.Return(); - AssertCaretVirtualPosition(3, 2); - } - - [WpfFact] - public async Task ReturnWithSelectionInReadonlyArea() - { - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - Window.InsertCode("23"); - - // Return() with selection in readonly area, no-op - // > 1 - // |1 | - // > 23 - MoveCaretToPreviousPosition(5); - AssertCaretVirtualPosition(1, 1); - - Window.Operations.SelectAll(); - - Window.Operations.Return(); - Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot()); - - // Return() with selection in active prompt - // > 1 - // 1 - // |> |23 - selection.Clear(); - MoveCaretToNextPosition(1); - var start = caret.Position.VirtualBufferPosition; - MoveCaretToNextPosition(2); - var end = caret.Position.VirtualBufferPosition; - AssertCaretVirtualPosition(2, 2); - - selection.Select(start, end); - - Window.Operations.Return(); - Assert.Equal("> 1\r\n1\r\n> \r\n> 23", GetTextFromCurrentSnapshot()); - - // Return() with selection overlaps with editable buffer, - // > 1 - // 1 - // > - // |> 2|3 - selection.Clear(); - MoveCaretToPreviousPosition(2); - start = caret.Position.VirtualBufferPosition; - MoveCaretToNextPosition(3); - end = caret.Position.VirtualBufferPosition; - AssertCaretVirtualPosition(3, 3); - - selection.Select(start, end); - - Window.Operations.Return(); - Assert.Equal("> 1\r\n1\r\n> \r\n> \r\n> 3", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(4, 2); - } - - [WpfFact] - public async Task DeleteLineWithOutSelection() - { - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - var caret = Window.TextView.Caret; - - // DeleteLine with caret in readonly area - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - caret.MoveToPreviousCaretPosition(); - - AssertCaretVirtualPosition(1, 1); - Window.Operations.DeleteLine(); - Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(1, 1); - - // DeleteLine with caret in active prompt - caret.MoveToNextCaretPosition(); - caret.MoveToNextCaretPosition(); - caret.MoveToNextCaretPosition(); - Window.InsertCode("int x"); - Window.Operations.BreakLine(); - Window.InsertCode(";"); - for (int i = 0; i < 11; ++i) - { - caret.MoveToPreviousCaretPosition(); - } - - AssertCaretVirtualPosition(2, 0); - Window.Operations.DeleteLine(); - Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(2, 2); - - // DeleteLine with caret in editable area - caret.MoveToNextCaretPosition(); - - Window.Operations.DeleteLine(); - Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(2, 2); - } - - [WpfFact] - public async Task DeleteLineWithSelection() - { - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - await Submit( -@"1", -@"1 -").ConfigureAwait(true); - - // DeleteLine with selection in readonly area - // > 1 - // |1 | - // > - MoveCaretToPreviousPosition(3); - Window.Operations.SelectAll(); - Window.Operations.DeleteLine(); - Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot()); - - // DeleteLine with selection in active prompt - // > 1 - // 1 - // |>| int x - // > ; - selection.Clear(); - MoveCaretToNextPosition(3); - Window.InsertCode("int x"); - Window.Operations.BreakLine(); - Window.InsertCode(";"); - MoveCaretToPreviousPosition(11); - var start = caret.Position.VirtualBufferPosition; - MoveCaretToNextPosition(1); - var end = caret.Position.VirtualBufferPosition; - selection.Select(start, end); - Window.Operations.DeleteLine(); - Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(2, 2); - Assert.True(selection.IsEmpty); - - // DeleteLine with selection in editable area - // > 1 - // 1 - // > int |x|; - Window.InsertCode("int x"); - MoveCaretToPreviousPosition(1); - start = caret.Position.VirtualBufferPosition; - MoveCaretToNextPosition(1); - end = caret.Position.VirtualBufferPosition; - selection.Select(start, end); - Window.Operations.DeleteLine(); - Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot()); - AssertCaretVirtualPosition(2, 2); - Assert.True(selection.IsEmpty); - - // DeleteLine with selection spans all areas, no-op - Window.InsertCode("int x"); - Window.Operations.BreakLine(); - Window.InsertCode(";"); - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - Window.Operations.DeleteLine(); - Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task SubmitAsyncNone() - { - await SubmitAsync().ConfigureAwait(true); - } - - [WpfFact] - public async Task SubmitAsyncSingle() - { - await SubmitAsync("1").ConfigureAwait(true); - } - - [WorkItem(5964, "https://github.com/dotnet/roslyn/issues/5964")] - [WpfFact] - public async Task SubmitAsyncMultiple() - { - await SubmitAsync("1", "2", "1 + 2").ConfigureAwait(true); - } - - [WorkItem(8569, "https://github.com/dotnet/roslyn/issues/8569")] - [WpfFact] - public async Task SubmitAsyncEmptyLine() - { - await SubmitAsync("1", "", "1 + 2").ConfigureAwait(true); - } - - private async Task SubmitAsync(params string[] submissions) - { - var actualSubmissions = new List(); - var evaluator = _testHost.Evaluator; - EventHandler onExecute = (_, s) => actualSubmissions.Add(s.TrimEnd()); - - evaluator.OnExecute += onExecute; - await TaskRun(() => Window.SubmitAsync(submissions)).ConfigureAwait(true); - evaluator.OnExecute -= onExecute; - - AssertEx.Equal(submissions, actualSubmissions); - } - - [WpfFact] - public void AddToHistory_EmptyLine() - { - var original = new InteractiveWindowTextSnapshot(_testHost); - Window.AddToHistory(""); - - var actual = new InteractiveWindowTextSnapshot(_testHost); - InteractiveWindowTextSnapshot.AssertEqual(original, actual); - } - - [WpfFact] - public void AddToHistory_NewLine() - { - var original = new InteractiveWindowTextSnapshot(_testHost); - Window.AddToHistory(Environment.NewLine); - - var actual = new InteractiveWindowTextSnapshot(_testHost); - var expected = original - .InsertBeforeLastPrompt(_testHost.Evaluator.GetPrompt(), ReplSpanKind.Prompt) - .InsertBeforeLastPrompt(Environment.NewLine, ReplSpanKind.Input); - - InteractiveWindowTextSnapshot.AssertEqual(expected, actual); - } - - [WpfFact] - public async Task AddToHistory_BetweenWrites() - { - var original = new InteractiveWindowTextSnapshot(_testHost); - - await Task.Run(() => Window.WriteLine("a")); - await Task.Run(() => Window.WriteLine("b")); - - Window.AddToHistory("c"); - - await Task.Run(() => Window.WriteLine("d")); - await Task.Run(() => Window.WriteLine("e")); - - Window.FlushOutput(); - - var actual = new InteractiveWindowTextSnapshot(_testHost); - var expected = original - .InsertBeforeLastPrompt($"a{Environment.NewLine}b{Environment.NewLine}", ReplSpanKind.Output) - .InsertBeforeLastPrompt(_testHost.Evaluator.GetPrompt(), ReplSpanKind.Prompt) - .InsertBeforeLastPrompt($"c{Environment.NewLine}", ReplSpanKind.Input) - .InsertBeforeLastPrompt($"d{Environment.NewLine}e{Environment.NewLine}", ReplSpanKind.Output); - - InteractiveWindowTextSnapshot.AssertEqual(expected, actual); - } - - [WpfFact] - public async Task AddToHistory_HistoryNavigation() - { - await Task.Run(() => Window.WriteLine("a")); - Window.AddToHistory("b"); - await Task.Run(() => Window.WriteLine("c")); - Window.AddToHistory("d"); - await Task.Run(() => Window.WriteLine("e")); - Window.FlushOutput(); - Window.Operations.TypeChar('f'); - - Assert.Equal("f", Window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); - - Window.Operations.HistoryPrevious(); - Assert.Equal("d", Window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); - - Window.Operations.HistoryPrevious(); - Assert.Equal("b", Window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); - - Window.Operations.HistoryNext(); - Assert.Equal("d", Window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); - - Window.Operations.HistoryNext(); - Assert.Equal("f", Window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); - } - - [WpfFact] - public void AddToHistory_HasInput() - { - var original = new InteractiveWindowTextSnapshot(_testHost); - - Window.Operations.TypeChar('a'); - Window.Operations.TypeChar('b'); - Window.AddToHistory("c"); - Window.Operations.TypeChar('d'); - Window.Operations.TypeChar('e'); - Window.AddToHistory("f"); - - var actual = new InteractiveWindowTextSnapshot(_testHost); - var expected = original - .InsertBeforeLastPrompt(_testHost.Evaluator.GetPrompt(), ReplSpanKind.Prompt) - .InsertBeforeLastPrompt($"c{Environment.NewLine}", ReplSpanKind.Input) - .InsertBeforeLastPrompt(_testHost.Evaluator.GetPrompt(), ReplSpanKind.Prompt) - .InsertBeforeLastPrompt($"f{Environment.NewLine}", ReplSpanKind.Input) - .AddToTheEnd($"abde", ReplSpanKind.Input); - - InteractiveWindowTextSnapshot.AssertEqual(expected, actual); - } - - - [WorkItem(6397, "https://github.com/dotnet/roslyn/issues/6397")] - [WpfFact] - public void TypeCharWithUndoRedo() - { - Window.Operations.TypeChar('a'); - Window.Operations.TypeChar('b'); - Window.Operations.TypeChar('c'); - Assert.Equal("> abc", GetTextFromCurrentSnapshot()); - - // undo/redo for consecutive TypeChar's shold be a single action - - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - ((InteractiveWindow)Window).Redo_TestOnly(1); - Assert.Equal("> abc", GetTextFromCurrentSnapshot()); - - // make a stream selection as follows: - // > |aaa| - Window.Operations.SelectAll(); - Window.Operations.TypeChar('1'); - Window.Operations.TypeChar('2'); - Window.Operations.TypeChar('3'); - - Assert.Equal("> 123", GetTextFromCurrentSnapshot()); - - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> abc", GetTextFromCurrentSnapshot()); - - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - // type in active prompt - MoveCaretToPreviousPosition(2); - Window.Operations.TypeChar('x'); - Window.Operations.TypeChar('y'); - Window.Operations.TypeChar('z'); - Assert.Equal("> xyz", GetTextFromCurrentSnapshot()); - } - - // TODO (https://github.com/dotnet/roslyn/issues/7976): delete this - [WorkItem(7976, "https://github.com/dotnet/roslyn/issues/7976")] - [WpfFact] - public void Workaround7976() - { - Thread.Sleep(TimeSpan.FromSeconds(10)); - } - - private string GetTextFromCurrentSnapshot() - { - return Window.TextView.TextBuffer.CurrentSnapshot.GetText(); - } - - private async Task Submit(string submission, string output) - { - await TaskRun(() => Window.SubmitAsync(new[] { submission })).ConfigureAwait(true); - // TestInteractiveEngine.ExecuteCodeAsync() simply returns - // success rather than executing the submission, so add the - // expected output to the output buffer. - var buffer = Window.OutputBuffer; - using (var edit = buffer.CreateEdit()) - { - edit.Replace(buffer.CurrentSnapshot.Length, 0, output); - edit.Apply(); - } - } - - private struct TextChange - { - internal readonly int Start; - internal readonly int Length; - internal readonly string Text; - - internal TextChange(int start, int length, string text) - { - Start = start; - Length = length; - Text = text; - } - } - - private static ITextSnapshot ApplyChanges(ITextBuffer buffer, params TextChange[] changes) - { - using (var edit = buffer.CreateEdit()) - { - foreach (var change in changes) - { - edit.Replace(change.Start, change.Length, change.Text); - } - return edit.Apply(); - } - } - - private class InteractiveWindowTextSnapshot - { - private readonly ImmutableArray _spans; - private readonly string _fullText; - - public InteractiveWindowTextSnapshot(InteractiveWindowTestHost host) - { - var bufferFactory = host.ExportProvider.GetExportedValue(); - var projectionSnapshot = ((IProjectionBuffer) host.Window.TextView.TextBuffer).CurrentSnapshot; - - _fullText = projectionSnapshot.GetText(); - _spans = projectionSnapshot.GetSourceSpans() - .SelectMany(ss => GetSpanWithKind(ss, projectionSnapshot, host.Window, bufferFactory.InertContentType)) - .OrderBy(s => s.Start) - .ToImmutableArray(); - } - - private InteractiveWindowTextSnapshot(string fullText, ImmutableArray spans) - { - _fullText = fullText; - _spans = spans; - } - - public InteractiveWindowTextSnapshot AddToTheEnd(string text, ReplSpanKind kind) - { - var startIndex = _fullText.Length; - var fullText = _fullText + text; - var spans = _spans.Add(new SpanWithKind(startIndex, text.Length, kind)); - - return new InteractiveWindowTextSnapshot(fullText, spans); - } - - public InteractiveWindowTextSnapshot InsertBeforeLastPrompt(string text, ReplSpanKind kind) - { - var startIndex = _spans.LastOrDefault(s => s.Kind == ReplSpanKind.Prompt).Start; - return Insert(text, startIndex, kind); - } - - private InteractiveWindowTextSnapshot Insert(string text, int startIndex, ReplSpanKind kind) - { - var length = text.Length; - var spansBuilder = ImmutableArray.CreateBuilder(_spans.Length + 1); - - var fullText = _fullText.Insert(startIndex, text); - foreach (var span in _spans) - { - if (span.Start < startIndex) - { - spansBuilder.Add(span); - } - else if (span.Start == startIndex) - { - spansBuilder.Add(new SpanWithKind(startIndex, length, kind)); - spansBuilder.Add(new SpanWithKind(span.Start + length, span.Length, span.Kind)); - } - else - { - spansBuilder.Add(new SpanWithKind(span.Start + length, span.Length, span.Kind)); - } - } - - return new InteractiveWindowTextSnapshot(fullText, spansBuilder.ToImmutable()); - } - - public static void AssertEqual(InteractiveWindowTextSnapshot expected, InteractiveWindowTextSnapshot actual) - { - Assert.Equal(expected._fullText, actual._fullText); - Assert.Equal(expected._spans, actual._spans); - } - - private static IEnumerable GetSpanWithKind(SnapshotSpan snapshotSpan, IProjectionSnapshot projectionSnapshot, IInteractiveWindow window, IContentType inertContentType) - { - var spans = projectionSnapshot.MapFromSourceSnapshot(snapshotSpan); - var spanKind = GetSpanKind(snapshotSpan, window, inertContentType); - return spans.Where(s => s.Length > 0).Select(span => new SpanWithKind(span.Start, span.Length, spanKind)); - } - - private static ReplSpanKind GetSpanKind(SnapshotSpan span, IInteractiveWindow window, IContentType inertContentType) - { - var textBuffer = span.Snapshot.TextBuffer; - - if (textBuffer == window.OutputBuffer) - { - return ReplSpanKind.Output; - } - - if (textBuffer.ContentType == inertContentType) - { - return ReplSpanKind.Prompt; - } - - return ReplSpanKind.Input; - } - - [DebuggerDisplay("{Start}, {Length}, {Kind}")] - private struct SpanWithKind : IEquatable - { - public int Start { get; } - public int Length { get; } - public ReplSpanKind Kind { get; } - - public SpanWithKind(int start, int length, ReplSpanKind kind) - { - Start = start; - Length = length; - Kind = kind; - } - - public bool Equals(SpanWithKind other) - { - return Start == other.Start && Length == other.Length && Kind == other.Kind; - } - - public override bool Equals(object obj) - { - return obj is SpanWithKind && Equals((SpanWithKind)obj); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = Start; - hashCode = (hashCode*397) ^ Length; - hashCode = (hashCode*397) ^ (int) Kind; - return hashCode; - } - } - } - } - } - - internal static class WindowExtensions - { - internal static void AddToHistory(this IInteractiveWindow window, string input) - { - ((IInteractiveWindow2)window).AddToHistory(input); - } - } - - internal static class OperationsExtensions - { - internal static void Copy(this IInteractiveWindowOperations operations) - { - ((IInteractiveWindowOperations2)operations).Copy(); - } - - internal static void CopyCode(this IInteractiveWindowOperations operations) - { - ((IInteractiveWindowOperations2)operations).CopyCode(); - } - - internal static void DeleteLine(this IInteractiveWindowOperations operations) - { - ((IInteractiveWindowOperations2)operations).DeleteLine(); - } - - internal static void CutLine(this IInteractiveWindowOperations operations) - { - ((IInteractiveWindowOperations2)operations).CutLine(); - } - - internal static void TypeChar(this IInteractiveWindowOperations operations, char typedChar) - { - ((IInteractiveWindowOperations2)operations).TypeChar(typedChar); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/InteractiveWindowTests_ClipboardTests.cs b/src/InteractiveWindow/EditorTest/InteractiveWindowTests_ClipboardTests.cs deleted file mode 100644 index 2f1614c484ac1..0000000000000 --- a/src/InteractiveWindow/EditorTest/InteractiveWindowTests_ClipboardTests.cs +++ /dev/null @@ -1,1759 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using Microsoft.VisualStudio.Text; -using Roslyn.Test.Utilities; -using Xunit; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public partial class InteractiveWindowTests : IDisposable - { - [WpfFact] - public void CopyStreamSelectionWithinInput() - { - _testClipboard.Clear(); - - Window.InsertCode("1 + 2"); - Window.Operations.SelectAll(); - Window.Operations.Copy(); - VerifyClipboardData("1 + 2", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 1 + 2}", - "[{\"content\":\"1 + 2\",\"kind\":2}]"); - - // Shrink the selection. - var selection = Window.TextView.Selection; - var span = selection.SelectedSpans[0]; - selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 1, span.Length - 2), isReversed: false); - - Window.Operations.Copy(); - VerifyClipboardData(" + ", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 + }", - @"[{""content"":"" + "",""kind"":2}]"); - } - - [WpfFact] - public void CopyStreamSelectionInputAndActivePrompt() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a stream selection as follows: - // > |111 - // > 222| - Window.Operations.SelectAll(); - Window.Operations.Copy(); - VerifyClipboardData("111\r\n> 222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111\\par > 222}", - "[{\"content\":\"111\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\",\"kind\":2}]"); - } - - [WpfFact] - public async Task CopyStreamSelectionInputAndOutput() - { - _testClipboard.Clear(); - - await Submit( -@"foreach (var o in new[] { 1, 2, 3 }) -System.Console.WriteLine(o);", -@"1 -2 -3 -").ConfigureAwait(true); - Window.InsertCode("1 + 2"); - - // make a stream selection as follows: - // |> foreach (var o in new[] { 1, 2, 3 }) - // > System.Console.WriteLine(o); - // 1 - // 2 - // 3 - // > 1 + 2| - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - Window.Operations.Copy(); - VerifyClipboardData("> foreach (var o in new[] { 1, 2, 3 })\r\n> System.Console.WriteLine(o);\r\n1\r\n2\r\n3\r\n> 1 + 2", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > foreach (var o in new[] \\{ 1, 2, 3 \\})\\par > System.Console.WriteLine(o);\\par 1\\par 2\\par 3\\par > 1 + 2}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"foreach (var o in new[] { 1, 2, 3 })\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"System.Console.WriteLine(o);\\u000d\\u000a\",\"kind\":2},{\"content\":\"1\\u000d\\u000a2\\u000d\\u000a3\\u000d\\u000a\",\"kind\":1},{\"content\":\"> \",\"kind\":0},{\"content\":\"1 + 2\",\"kind\":2}]"); - - // Shrink the selection. - var selection = Window.TextView.Selection; - var span = selection.SelectedSpans[0]; - selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false); - - Window.Operations.Copy(); - VerifyClipboardData("oreach (var o in new[] { 1, 2, 3 })\r\n> System.Console.WriteLine(o);\r\n1\r\n2\r\n3\r\n> 1 ", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 oreach (var o in new[] \\{ 1, 2, 3 \\})\\par > System.Console.WriteLine(o);\\par 1\\par 2\\par 3\\par > 1 }", - "[{\"content\":\"oreach (var o in new[] { 1, 2, 3 })\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"System.Console.WriteLine(o);\\u000d\\u000a\",\"kind\":2},{\"content\":\"1\\u000d\\u000a2\\u000d\\u000a3\\u000d\\u000a\",\"kind\":1},{\"content\":\"> \",\"kind\":0},{\"content\":\"1 \",\"kind\":2}]"); - } - - [WpfFact] - public void CopyBoxSelectionWithinInput() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a box selection as follows: - // > 11|1| - // > 22|2| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - Window.Operations.Copy(); - VerifyClipboardData("1\r\n2\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 1\\par 2}", - "[{\"content\":\"1\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"2\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4}]", - expectedToBeBoxCopy: true); - } - - [WpfFact] - public void CopyBoxSelectionInputAndActivePrompt() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a box selection as follows: - // |> 111| - // |> 222| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(11); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - Window.Operations.Copy(); - VerifyClipboardData("> 111\r\n> 222\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par > 222}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4}]", - expectedToBeBoxCopy: true); - } - - [WpfFact] - public async Task CopyBoxSelectionInputAndOutput() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - await Submit( -@"11111", -@"11111 -").ConfigureAwait(true); - - Window.InsertCode("222"); - - // make a box selection as follows: - // 1111|1| - // > 22|2| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - Window.Operations.Copy(); - VerifyClipboardData("1\r\n2\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 1\\par 2}", - "[{\"content\":\"1\",\"kind\":1},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"2\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4}]", - expectedToBeBoxCopy: true); - } - - [WpfFact] - public void CutStreamSelectionWithinInputThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - - // make a stream selection as follows: - // > |111| - Window.Operations.SelectAll(); - - Window.Operations.Cut(); - - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - Assert.True(Window.TextView.Selection.IsEmpty); - - VerifyClipboardData("111", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111}", - "[{\"content\":\"111\",\"kind\":2}]"); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void CutStreamSelectionInputAndActivePromptThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a stream selection as follows: - // > |111 - // > 222| - Window.Operations.SelectAll(); - Window.Operations.Cut(); - - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - Assert.True(Window.TextView.Selection.IsEmpty); - - VerifyClipboardData("111\r\n> 222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111\\par > 222}", - "[{\"content\":\"111\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\",\"kind\":2}]"); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task CutStreamSelectionInputAndOutput() - { - _testClipboard.Clear(); - - await Submit( -@"foreach (var o in new[] { 1, 2, 3 }) -System.Console.WriteLine();", -@"1 -2 -3 -").ConfigureAwait(true); - Window.InsertCode("1 + 2"); - - // make a stream selection as follows: - // |> foreach (var o in new[] { 1, 2, 3 }) - // > System.Console.WriteLine(o); - // 1 - // 2 - // 3 - // > 1 + 2| - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - Window.Operations.Cut(); - - // expect nothing got deleted - Assert.Equal("> foreach (var o in new[] { 1, 2, 3 })\r\n> System.Console.WriteLine();\r\n1\r\n2\r\n3\r\n> 1 + 2", - GetTextFromCurrentSnapshot()); - Assert.False(Window.TextView.Selection.IsEmpty); - - // everything got copied to clipboard - VerifyClipboardData("> foreach (var o in new[] { 1, 2, 3 })\r\n> System.Console.WriteLine();\r\n1\r\n2\r\n3\r\n> 1 + 2", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > foreach (var o in new[] \\{ 1, 2, 3 \\})\\par > System.Console.WriteLine();\\par 1\\par 2\\par 3\\par > 1 + 2}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"foreach (var o in new[] { 1, 2, 3 })\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"System.Console.WriteLine();\\u000d\\u000a\",\"kind\":2},{\"content\":\"1\\u000d\\u000a2\\u000d\\u000a3\\u000d\\u000a\",\"kind\":1},{\"content\":\"> \",\"kind\":0},{\"content\":\"1 + 2\",\"kind\":2}]"); - } - - [WpfFact] - public void CutBoxSelectionWithinInputThenUndo() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a box selection as follows: - // > 11|1| - // > 22|2| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - Window.Operations.Cut(); - - // expected snapshot after cut: - // > 11 - // > 22 - Assert.Equal("> 11\r\n> 22", GetTextFromCurrentSnapshot()); - Assert.True(IsEmptyBoxSelection()); - - VerifyClipboardData("1\r\n2\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 1\\par 2}", - "[{\"content\":\"1\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"2\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4}]", - expectedToBeBoxCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void CutBoxSelectionInputAndActivePromptThenUndo() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a box selection as follows: - // |> 111| - // |> 222| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(11); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - Window.Operations.Cut(); - - // expected snapshot after cut: - // > - // > - Assert.Equal("> \r\n> ", GetTextFromCurrentSnapshot()); - Assert.True(IsEmptyBoxSelection()); - - VerifyClipboardData("> 111\r\n> 222\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par > 222}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4}]", - expectedToBeBoxCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task CutBoxSelectionInputAndOutput() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - await Submit( -@"11111", -@"11111 -").ConfigureAwait(true); - - Window.InsertCode("222"); - Window.Operations.BreakLine(); - Window.InsertCode("333"); - - // make a box selection as follows: - // 1111|1| - // > 22|2| - // > 33|3| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(13); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - // expected snapshot after cut: - // 11111 - // > 222 - // > 333 - Window.Operations.Cut(); - - Assert.Equal("> 11111\r\n11111\r\n> 222\r\n> 333", GetTextFromCurrentSnapshot()); - Assert.False(Window.TextView.Selection.IsEmpty); - Assert.True(Window.TextView.Selection.Mode == Text.Editor.TextSelectionMode.Box); - Assert.False(IsEmptyBoxSelection()); - - VerifyClipboardData("1\r\n2\r\n3\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 1\\par 2\\par 3}", - "[{\"content\":\"1\",\"kind\":1},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"2\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"3\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4}]", - expectedToBeBoxCopy: true); - } - - /// - /// When there is no selection, copy - /// should copy the current line. - /// - [WpfFact] - public async Task CopyNoSelection() - { - await Submit( -@"s + - - t", -@" 1 - -22 -").ConfigureAwait(true); - Window.InsertCode("1 + 2"); - - // readonly buffer - CopyNoSelectionAndVerify(0, 7, "> s +\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > s +\\par }", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"s +\\u000d\\u000a\",\"kind\":2}]"); - CopyNoSelectionAndVerify(7, 11, "> \r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > \\par }", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"\\u000d\\u000a\",\"kind\":2}]"); - CopyNoSelectionAndVerify(11, 17, "> t\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > t\\par }", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\" t\\u000d\\u000a\",\"kind\":2}]"); - CopyNoSelectionAndVerify(17, 21, " 1\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 1\\par }", - "[{\"content\":\" 1\\u000d\\u000a\",\"kind\":1}]"); - CopyNoSelectionAndVerify(21, 23, "\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 \\par }", - "[{\"content\":\"\\u000d\\u000a\",\"kind\":1}]"); - CopyNoSelectionAndVerify(23, 27, "22\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 22\\par }", - "[{\"content\":\"22\\u000d\\u000a\",\"kind\":1}]"); - - // editable buffer and active prompt - CopyNoSelectionAndVerify(27, 34, "> 1 + 2", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 1 + 2}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"1 + 2\",\"kind\":2}]"); - } - - [WpfFact] - public void CutNoSelectionInInputThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - - // caret at" - // > 11|1 - MoveCaretToPreviousPosition(1); - Window.Operations.Cut(); - - // expected snapshot after cut: - // > - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("> 111", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void CutNoSelectionInActivePromptThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - - // caret at" - // > 11|1 - MoveCaretToPreviousPosition(5); - Window.Operations.Cut(); - - // expected snapshot after cut: - // > - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("> 111", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task CutNoSelectionInReadOnly() - { - _testClipboard.Clear(); - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - - // caret at" - // > 111 - // 11|1 - // > - MoveCaretToPreviousPosition(4); - Window.Operations.Cut(); - - // expected snapshot after cut: - // > - Assert.Equal("> 111\r\n111\r\n> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("111\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111\\par }", - "[{\"content\":\"111\\u000d\\u000a\",\"kind\":1}]", - expectedToBeLineCopy: true); - - // caret in non-active prompt" - // |> 111 - // 111 - // > - MoveCaretToPreviousPosition(8); - Window.Operations.Cut(); - - Assert.Equal("> 111\r\n111\r\n> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("> 111\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par }", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\\u000d\\u000a\",\"kind\":2}]", - expectedToBeLineCopy: true); - } - - [WpfFact] - public void Paste() - { - var blocks = new[] - { - new BufferBlock(ReplSpanKind.Output, "a\r\nbc"), - new BufferBlock(ReplSpanKind.Prompt, "> "), - new BufferBlock(ReplSpanKind.Prompt, "< "), - new BufferBlock(ReplSpanKind.Input, "12"), - new BufferBlock(ReplSpanKind.StandardInput, "3"), - new BufferBlock((ReplSpanKind)10, "xyz") // this is invalid ReplSpanKind value - }; - - // Paste from text clipboard format. - CopyToClipboard(blocks, includeRepl: false); - Window.Operations.Paste(); - Assert.Equal("> a\r\n> bc> < 123xyz", GetTextFromCurrentSnapshot()); - - Window.Operations.ClearView(); - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - // Paste from custom clipboard format. - CopyToClipboard(blocks, includeRepl: true); - Window.Operations.Paste(); - Assert.Equal("> a\r\n> bc123", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void CutLineNoSelectionInInputThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - - // caret at" - // > 11|1 - MoveCaretToPreviousPosition(1); - Window.Operations.CutLine(); - - // expected snapshot after cut: - // > - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("> 111", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void CutLineNoSelectionInActivePromptThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - - // caret at" - // > 11|1 - MoveCaretToPreviousPosition(5); - Window.Operations.CutLine(); - - // expected snapshot after cut: - // > - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("> 111", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task CutLineNoSelectionInReadOnly() - { - _testClipboard.Clear(); - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - - // caret at" - // > 111 - // 11|1 - // > - MoveCaretToPreviousPosition(4); - Window.Operations.CutLine(); - - // expected snapshot after cut: - // > - Assert.Equal("> 111\r\n111\r\n> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("111\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111\\par }", - "[{\"content\":\"111\\u000d\\u000a\",\"kind\":1}]", - expectedToBeLineCopy: true); - - // caret in non-active prompt" - // |> 111 - // 111 - // > - MoveCaretToPreviousPosition(8); - Window.Operations.CutLine(); - - Assert.Equal("> 111\r\n111\r\n> ", GetTextFromCurrentSnapshot()); - - VerifyClipboardData("> 111\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par }", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\\u000d\\u000a\",\"kind\":2}]", - expectedToBeLineCopy: true); - } - - [WpfFact] - public void CutLineStreamSelectionWithinInputThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - // make a stream selection as follows: - // > 1|11| - // > 222 - MoveCaretToPreviousPosition(6); - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(2); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Stream; - selection.Select(anchor, active); - - Window.Operations.CutLine(); - - Assert.Equal("> 222", GetTextFromCurrentSnapshot()); - Assert.True(Window.TextView.Selection.IsEmpty); - - VerifyClipboardData("> 111\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par }", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\\u000d\\u000a\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void CutLineStreamSelectionInputAndActivePromptThenUndo() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - // make a stream selection as follows: - // > |111 - // >| 222 - MoveCaretToPreviousPosition(4); - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(5); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Stream; - selection.Select(anchor, active); - - Window.Operations.CutLine(); - - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - Assert.True(Window.TextView.Selection.IsEmpty); - - VerifyClipboardData("> 111\r\n> 222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par > 222}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task CutLineStreamSelectionInputAndOutput() - { - _testClipboard.Clear(); - - await Submit( -@"foreach (var o in new[] { 1, 2, 3 }) -System.Console.WriteLine();", -@"1 -2 -3 -").ConfigureAwait(true); - Window.InsertCode("1 + 2"); - - // make a stream selection as follows: - // |> foreach (var o in new[] { 1, 2, 3 }) - // > System.Console.WriteLine(o); - // 1 - // 2 - // 3 - // > 1 + 2| - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - Window.Operations.CutLine(); - - // expect nothing got deleted - Assert.Equal("> foreach (var o in new[] { 1, 2, 3 })\r\n> System.Console.WriteLine();\r\n1\r\n2\r\n3\r\n> 1 + 2", - GetTextFromCurrentSnapshot()); - Assert.False(Window.TextView.Selection.IsEmpty); - - // everything got copied to clipboard - VerifyClipboardData("> foreach (var o in new[] { 1, 2, 3 })\r\n> System.Console.WriteLine();\r\n1\r\n2\r\n3\r\n> 1 + 2", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > foreach (var o in new[] \\{ 1, 2, 3 \\})\\par > System.Console.WriteLine();\\par 1\\par 2\\par 3\\par > 1 + 2}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"foreach (var o in new[] { 1, 2, 3 })\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"System.Console.WriteLine();\\u000d\\u000a\",\"kind\":2},{\"content\":\"1\\u000d\\u000a2\\u000d\\u000a3\\u000d\\u000a\",\"kind\":1},{\"content\":\"> \",\"kind\":0},{\"content\":\"1 + 2\",\"kind\":2}]", - expectedToBeLineCopy: true); - } - - [WpfFact] - public void CutLineBoxSelectionWithinInputThenUndo() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a box selection as follows: - // > 11|1| - // > 22|2| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - Window.Operations.CutLine(); - - // expected snapshot after cut line: - // > - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - Assert.True(selection.IsEmpty); - - VerifyClipboardData("> 111\r\n> 222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par > 222}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void CutLineBoxSelectionInputAndActivePromptThenUndo() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a box selection as follows: - // |> 111| - // |> 222| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(11); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - Window.Operations.CutLine(); - - // expected snapshot after cut line: - // > - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - Assert.True(selection.IsEmpty); - - VerifyClipboardData("> 111\r\n> 222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 > 111\\par > 222}", - "[{\"content\":\"> \",\"kind\":0},{\"content\":\"111\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\",\"kind\":2}]", - expectedToBeLineCopy: true); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task CutLineBoxSelectionInputAndOutput() - { - _testClipboard.Clear(); - var caret = Window.TextView.Caret; - - await Submit( -@"11111", -@"11111 -").ConfigureAwait(true); - - Window.InsertCode("222"); - Window.Operations.BreakLine(); - Window.InsertCode("333"); - - // make a box selection as follows: - // 1111|1| - // > 22|2| - // > 33|3| - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(13); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - // expected snapshot after cut-line: - // 11111 - // > 222 - // > 333 - Window.Operations.CutLine(); - - Assert.Equal("> 11111\r\n11111\r\n> 222\r\n> 333", GetTextFromCurrentSnapshot()); - Assert.False(Window.TextView.Selection.IsEmpty); - Assert.True(Window.TextView.Selection.Mode == Text.Editor.TextSelectionMode.Box); - Assert.False(IsEmptyBoxSelection()); - - VerifyClipboardData("11111\r\n> 222\r\n> 333", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 11111\\par > 222\\par > 333}", - "[{\"content\":\"11111\\u000d\\u000a\",\"kind\":1},{\"content\":\"> \",\"kind\":0},{\"content\":\"222\\u000d\\u000a\",\"kind\":2},{\"content\":\"> \",\"kind\":0},{\"content\":\"333\",\"kind\":2}]", - expectedToBeLineCopy: true); - } - - [WpfFact] - public void PasteNoSelectionWithinInputThenUndo() - { - // paste text copied from stream selection - Window.InsertCode("111"); - MoveCaretToPreviousPosition(1); - - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 11TextCopiedFromStreamSelection1", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - - // paste text copied from copyline - // > 11|1 - Window.Operations.ClearView(); - Window.InsertCode("111"); - MoveCaretToPreviousPosition(1); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> TextCopiedFromLineSelection\r\n> 111", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - - // paste text copied from box selection into a blank line - // > | - // > 111 - Window.Operations.ClearView(); - Window.Operations.BreakLine(); - Window.InsertCode("111"); - MoveCaretToPreviousPosition(6); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - //TODO: Fix this - //Assert.Equal("> BoxLine1\r\n> BoxLine2\r\n> 111", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> \r\n> 111", GetTextFromCurrentSnapshot()); - - // paste text copied from box selection - // > 1|11 - // > 222 - Window.Operations.ClearView(); - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - MoveCaretToPreviousPosition(8); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 1BoxLine111\r\n> 2BoxLine222", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void PasteNoSelectionInActivePromptThenUndo() - { - // >| 111 - Window.InsertCode("111"); - MoveCaretToPreviousPosition(4); - - // paste text copied from stream selection - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> TextCopiedFromStreamSelection111", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - - // paste text copied from copyline - // |> 111 - Window.Operations.ClearView(); - Window.InsertCode("111"); - MoveCaretToPreviousPosition(5); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> TextCopiedFromLineSelection\r\n> 111", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - - // paste text copied from box selection - // >| 111 - // > 222 - Window.Operations.ClearView(); - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - MoveCaretToPreviousPosition(10); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> BoxLine1111\r\n> BoxLine2222", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task PasteNoSelectioninReadOnly() - { - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - - // > 111 - // 11|1 - // > - MoveCaretToPreviousPosition(4); - - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> ", GetTextFromCurrentSnapshot()); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> ", GetTextFromCurrentSnapshot()); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> ", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void PasteStreamSelectionWithinInputThenUndo() - { - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - Window.InsertCode("111"); - - // make a stream selection as follows: - // > 1|11| - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(2); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Stream; - selection.Select(anchor, active); - - // paste text copied from stream selection - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 1TextCopiedFromStreamSelection", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - - // paste text copied from copyline - Window.Operations.ClearView(); - Window.InsertCode("111"); - - // make a stream selection as follows: - // > 1|11| - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(2); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Stream; - selection.Select(anchor, active); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 1TextCopiedFromLineSelection\r\n> ", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - - // paste text copied from box selection - Window.Operations.ClearView(); - Window.InsertCode("111"); - - // make a stream selection as follows: - // > 1|11| - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(2); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Stream; - selection.Select(anchor, active); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - // TODO: Fix this, should be - // > 1BoxLine1 - // > BoxLine2 - Assert.Equal("> 1BoxLine1\r\n> BoxLine2", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void PasteStreamSelectionInputAndActivePromptThenUndo() - { - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a stream selection as follows: - // > |111 - // > 222| - Window.Operations.SelectAll(); - - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> TextCopiedFromStreamSelection", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - - // paste text copied from copyline - Window.Operations.ClearView(); - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - Window.Operations.SelectAll(); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> TextCopiedFromLineSelection\r\n> ", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - - // paste text copied from box selection - Window.Operations.ClearView(); - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - Window.Operations.SelectAll(); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - // > BoxLine1 - // > BoxLine2 - Assert.Equal("> BoxLine1\r\n> BoxLine2\r\n> ", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task PasteStreamSelectionInputAndOutput() - { - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - Window.InsertCode("222"); - - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> 222", GetTextFromCurrentSnapshot()); - - Window.TextView.Selection.Clear(); - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> 222", GetTextFromCurrentSnapshot()); - - Window.TextView.Selection.Clear(); - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void PasteBoxSelectionWithinInputThenUndo() - { - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - // stream copy - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make a box selection as follows: - // > 1|1|1 - // > 2|2|2 - MoveCaretToPreviousPosition(1); - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 1TextCopiedFromStreamSelection1\r\n> 2TextCopiedFromStreamSelection2", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - - // line copy - Window.Operations.ClearView(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - MoveCaretToPreviousPosition(1); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 1TextCopiedFromLineSelection\r\n> 1\r\n> 2TextCopiedFromLineSelection\r\n> 2", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - - // box copy - Window.Operations.ClearView(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - MoveCaretToPreviousPosition(1); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 1BoxLine11\r\n> 2BoxLine22", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public void PasteBoxSelectionInputAndActivePromptThenUndo() - { - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make an empty box selection as follows: - // >|| 111 - // >|| 222 - MoveCaretToPreviousPosition(4); - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> TextCopiedFromStreamSelection111\r\n> TextCopiedFromStreamSelection222", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - - Window.Operations.ClearView(); - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make an empty box selection as follows: - // >|| 111 - // >|| 222 - MoveCaretToPreviousPosition(4); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> TextCopiedFromLineSelection\r\n> 111\r\n> TextCopiedFromLineSelection\r\n> 222", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - - Window.Operations.ClearView(); - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make an empty box selection as follows: - // >|| 111 - // >|| 222 - MoveCaretToPreviousPosition(4); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - // TODO: fix , should be "> BoxLine1111\r\n> BoxLine2222" - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - - Window.Operations.ClearView(); - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // make an empty box selection as follows: - // |> 1|11 - // |> 2|22 - MoveCaretToPreviousPosition(2); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(9); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - Assert.Equal("> BoxLine111\r\n> BoxLine222", GetTextFromCurrentSnapshot()); - - // undo - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task PasteBoxSelectionInputAndOutput() - { - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - Window.InsertCode("222"); - - var caret = Window.TextView.Caret; - var selection = Window.TextView.Selection; - - // make a stream selection as follows: - // > 111 - // |111| - // |> 2|22 - MoveCaretToPreviousPosition(2); - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyStreamToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> 222", GetTextFromCurrentSnapshot()); - - Window.TextView.Selection.Clear(); - MoveCaretToPreviousPosition(2); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyLineToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> 222", GetTextFromCurrentSnapshot()); - - Window.TextView.Selection.Clear(); - MoveCaretToPreviousPosition(2); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - - CopyBoxToClipboard(); - Window.Operations.Paste(); - - Assert.Equal("> 111\r\n111\r\n> 222", GetTextFromCurrentSnapshot()); - } - - [WorkItem(6054, "https://github.com/dotnet/roslyn/issues/6054")] - [WpfFact] - public void UndoMultiLinePaste() - { - CopyToClipboard( -@"1 -2 -3"); - - // paste multi-line text - Window.Operations.Paste(); - Assert.Equal("> 1\r\n> 2\r\n> 3", GetTextFromCurrentSnapshot()); - - // undo paste - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - - // redo paste - ((InteractiveWindow)Window).Redo_TestOnly(1); - Assert.Equal("> 1\r\n> 2\r\n> 3", GetTextFromCurrentSnapshot()); - - - CopyToClipboard( -@"4 -5 -6"); - // replace current text - Window.Operations.SelectAll(); - Window.Operations.Paste(); - Assert.Equal("> 4\r\n> 5\r\n> 6", GetTextFromCurrentSnapshot()); - - // undo replace - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> 1\r\n> 2\r\n> 3", GetTextFromCurrentSnapshot()); - - // undo paste - ((InteractiveWindow)Window).Undo_TestOnly(1); - Assert.Equal("> ", GetTextFromCurrentSnapshot()); - } - - [WpfFact] - public async Task CopyInputsFromCurrentLine() - { - _testClipboard.Clear(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - Window.Operations.CopyCode(); - VerifyClipboardData("222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 222}", - "[{\"content\":\"222\",\"kind\":2}]", - expectedToBeLineCopy: true); - - - // Move caret to: - // > 1|11 - // > 222 - MoveCaretToPreviousPosition(7); - Window.Operations.CopyCode(); - VerifyClipboardData("111\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111\\par }", - "[{\"content\":\"111\\u000d\\u000a\",\"kind\":2}]", - expectedToBeLineCopy: true); - - _testClipboard.Clear(); - Window.Operations.ClearView(); - - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - - Window.InsertCode("222"); - - // Move caret to: - // > 111 - // 1|11 - // > 222 - MoveCaretToPreviousPosition(7); - Window.Operations.CopyCode(); - VerifyClipboardData(null, null, null); - } - - [WpfFact] - public async Task CopyInputsFromSelection() - { - _testClipboard.Clear(); - - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - Window.InsertCode("222"); - - // Make following stream selection: - // |> 111 - // 111 - // > 222| - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - Window.Operations.CopyCode(); - VerifyClipboardData("111\r\n222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111\\par 222}", - "[{\"content\":\"111\\u000d\\u000a\",\"kind\":2},{\"content\":\"222\",\"kind\":2}]"); - - - _testClipboard.Clear(); - Window.Operations.ClearView(); - - Window.InsertCode("111"); - Window.Operations.BreakLine(); - Window.InsertCode("222"); - - // Make a selection as follows: - // |> 111 - // > 222| - Window.Operations.SelectAll(); - Window.Operations.SelectAll(); - Window.Operations.CopyCode(); - - VerifyClipboardData("111\r\n222", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 111\\par 222}", - "[{\"content\":\"111\\u000d\\u000a\",\"kind\":2},{\"content\":\"222\",\"kind\":2}]"); - - _testClipboard.Clear(); - Window.TextView.Selection.Clear(); - - var caret = Window.TextView.Caret; - // Make a box selection as follows: - // |> 1|11 - // |111| - // |> 2|22 - MoveCaretToPreviousPosition(2); - var selection = Window.TextView.Selection; - var anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(13); - var active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Box; - selection.Select(anchor, active); - Window.Operations.CopyCode(); - - VerifyClipboardData("1\r\n2\r\n", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 1\\par 2}", - "[{\"content\":\"1\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4},{\"content\":\"2\",\"kind\":2},{\"content\":\"\\u000d\\u000a\",\"kind\":4}]", - expectedToBeBoxCopy: true); - - _testClipboard.Clear(); - Window.Operations.ClearView(); - - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - Window.InsertCode("222"); - - // Make a stream selection as follows: - // > 111 - // 1|11 - // > 22|2 - MoveCaretToPreviousPosition(1); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(7); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Stream; - selection.Select(anchor, active); - Window.Operations.CopyCode(); - - VerifyClipboardData("22", - "{\\rtf\\ansi{\\fonttbl{\\f0 Consolas;}}{\\colortbl;\\red0\\green0\\blue0;}\\f0 \\fs24 \\cf1 \\cb0 \\highlight0 22}", - "[{\"content\":\"22\",\"kind\":2}]"); - - _testClipboard.Clear(); - Window.Operations.ClearView(); - - await Submit( -@"111", -@"111 -").ConfigureAwait(true); - Window.InsertCode("222"); - - // Make a stream selection as follows: - // > 111 - // 1|11| - // > 222 - MoveCaretToPreviousPosition(6); - anchor = caret.Position.VirtualBufferPosition; - MoveCaretToPreviousPosition(2); - active = caret.Position.VirtualBufferPosition; - selection.Mode = Text.Editor.TextSelectionMode.Stream; - selection.Select(anchor, active); - Window.Operations.CopyCode(); - - VerifyClipboardData(null, null, null); - } - - /// - /// Put text equivalent to copying from following selection to clipboard: - /// |> TextCopiedFromStreamSelection| - /// - private void CopyStreamToClipboard() - { - var blocks = new[] - { - new BufferBlock(ReplSpanKind.Prompt, "> "), - new BufferBlock(ReplSpanKind.Input, "TextCopiedFromStreamSelection"), - }; - - CopyToClipboard(blocks, includeRepl: true); - } - - /// - /// Put text equivalent to line-copying from following selection to clipboard: - /// > TextCopiedFromLineSel|ection - /// > - /// - private void CopyLineToClipboard() - { - var blocks = new[] - { - new BufferBlock(ReplSpanKind.Prompt, "> "), - new BufferBlock(ReplSpanKind.Input, "TextCopiedFromLineSelection\r\n"), - }; - - CopyToClipboard(blocks, includeRepl: true, isLineCopy: true); - } - - /// - /// Put text equivalent to copying from following box selection to clipboard: - /// > 1|1|1 - /// > 2|2|2 - /// - private void CopyBoxToClipboard() - { - var blocks = new[] - { - new BufferBlock(ReplSpanKind.Input, "BoxLine1"), - new BufferBlock(ReplSpanKind.LineBreak, "\r\n"), - new BufferBlock(ReplSpanKind.Input, "BoxLine2"), - new BufferBlock(ReplSpanKind.LineBreak, "\r\n"), - }; - - CopyToClipboard(blocks, includeRepl: true, isBoxCopy: true); - } - - private void CopyToClipboard(string text) - { - _testClipboard.Clear(); - var data = new DataObject(); - data.SetData(DataFormats.UnicodeText, text); - data.SetData(DataFormats.StringFormat, text); - _testClipboard.SetDataObject(data, false); - } - - private void CopyToClipboard(BufferBlock[] blocks, bool includeRepl, bool isLineCopy = false, bool isBoxCopy = false) - { - _testClipboard.Clear(); - var data = new DataObject(); - var builder = new StringBuilder(); - foreach (var block in blocks) - { - builder.Append(block.Content); - } - var text = builder.ToString(); - data.SetData(DataFormats.UnicodeText, text); - data.SetData(DataFormats.StringFormat, text); - if (includeRepl) - { - data.SetData(InteractiveClipboardFormat.Tag, BufferBlock.Serialize(blocks)); - } - if (isLineCopy) - { - data.SetData(InteractiveWindow.ClipboardLineBasedCutCopyTag, true); - } - if (isBoxCopy) - { - data.SetData(InteractiveWindow.BoxSelectionCutCopyTag, true); - } - _testClipboard.SetDataObject(data, false); - } - - private void VerifyClipboardData(string expectedText, string expectedRtf, string expectedRepl, bool expectedToBeLineCopy = false, bool expectedToBeBoxCopy = false) - { - var data = _testClipboard.GetDataObject(); - Assert.Equal(expectedText, data?.GetData(DataFormats.StringFormat)); - Assert.Equal(expectedText, data?.GetData(DataFormats.Text)); - Assert.Equal(expectedText, data?.GetData(DataFormats.UnicodeText)); - Assert.Equal(expectedRepl, (string)data?.GetData(InteractiveClipboardFormat.Tag)); - var actualRtf = (string)data?.GetData(DataFormats.Rtf); - if (expectedRtf == null) - { - Assert.Null(actualRtf); - } - else - { - Assert.Equal(expectedRtf, actualRtf); - } - - Assert.Equal(expectedToBeLineCopy, data?.GetDataPresent(InteractiveWindow.ClipboardLineBasedCutCopyTag) ?? false); - Assert.Equal(expectedToBeBoxCopy, data?.GetDataPresent(InteractiveWindow.BoxSelectionCutCopyTag) ?? false); - Assert.False(expectedToBeLineCopy && expectedToBeBoxCopy); - } - - private void CopyNoSelectionAndVerify(int start, int end, string expectedText, string expectedRtf, string expectedRepl) - { - var caret = Window.TextView.Caret; - var snapshot = Window.TextView.TextBuffer.CurrentSnapshot; - for (int i = start; i < end; i++) - { - _testClipboard.Clear(); - caret.MoveTo(new SnapshotPoint(snapshot, i)); - Window.Operations.Copy(); - VerifyClipboardData(expectedText, expectedRtf, expectedRepl, expectedToBeLineCopy: true); - } - } - - private void MoveCaretToPreviousPosition(int moves = 1) - { - var caret = Window.TextView.Caret; - for (int i = 0; i < moves; ++i) - { - caret.MoveToPreviousCaretPosition(); - } - } - - private void MoveCaretToNextPosition(int moves = 1) - { - var caret = Window.TextView.Caret; - for (int i = 0; i < moves; ++i) - { - caret.MoveToNextCaretPosition(); - } - } - - private bool IsEmptyBoxSelection() - { - return !Window.TextView.Selection.IsEmpty && - Window.TextView.Selection.VirtualSelectedSpans.All(s => s.IsEmpty); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/Microsoft.VisualStudio.InteractiveWindow.UnitTests.xunit.runner.json b/src/InteractiveWindow/EditorTest/Microsoft.VisualStudio.InteractiveWindow.UnitTests.xunit.runner.json deleted file mode 100644 index 78c070e83207b..0000000000000 --- a/src/InteractiveWindow/EditorTest/Microsoft.VisualStudio.InteractiveWindow.UnitTests.xunit.runner.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "shadowCopy": false -} \ No newline at end of file diff --git a/src/InteractiveWindow/EditorTest/SortedSpansTests.cs b/src/InteractiveWindow/EditorTest/SortedSpansTests.cs deleted file mode 100644 index b008164f88aeb..0000000000000 --- a/src/InteractiveWindow/EditorTest/SortedSpansTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.Text; -using Xunit; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public class SortedSpansTests - { - [Fact] - public void CheckOverlap() - { - var spans = new SortedSpans(); - - // no overlap with empty span list - Assert.Empty(spans.GetOverlap(new Span(0, 10))); - - // add span [10, 20) - spans.Add(new Span(10, 10)); - // no overlap with [0, 5) - Assert.Empty(spans.GetOverlap(new Span(0, 5))); - // no overlap with [25, 30) - Assert.Empty(spans.GetOverlap(new Span(25, 5))); - // no overlap with [0, 10) - Assert.Empty(spans.GetOverlap(new Span(0, 10))); - // no overlap with [20, 30) - Assert.Empty(spans.GetOverlap(new Span(20, 10))); - // overlap with [5, 15) - Assert.Equal(new Span[] { new Span(10, 5) }, - spans.GetOverlap(new Span(5, 10))); - // overlap with [0, 11) - Assert.Equal(new Span[] { new Span(10, 1) }, - spans.GetOverlap(new Span(0, 11))); - // overlap with [15, 25) - Assert.Equal(new Span[] { new Span(15, 5) }, - spans.GetOverlap(new Span(15, 10))); - // overlap with [11, 15] - Assert.Equal(new Span[] { new Span(11, 5) }, - spans.GetOverlap(new Span(11, 5))); - // overlap with [10, 20) - Assert.Equal(new Span[] { new Span(10, 10) }, - spans.GetOverlap(new Span(10, 10))); - // overlap with [0, 30) - Assert.Equal(new Span[] { new Span(10, 10) }, - spans.GetOverlap(new Span(0, 30))); - - // no overlap with [0, 0] - Assert.Empty(spans.GetOverlap(new Span(0, 0))); - // no overlap with [10, 10] - Assert.Empty(spans.GetOverlap(new Span(10, 0))); - // no overlap with [15, 15] - Assert.Empty(spans.GetOverlap(new Span(15, 0))); - - // now has both [10, 20) and [30, 40) - spans.Add(new Span(30, 10)); - - // no overlap with [20, 30) - Assert.Empty(spans.GetOverlap(new Span(20, 10))); - // no overlap with [0, 10) - Assert.Empty(spans.GetOverlap(new Span(0, 10))); - // no overlap with [40, 50) - Assert.Empty(spans.GetOverlap(new Span(40, 10))); - - // overlap with [0, 15) - Assert.Equal(new Span[] { new Span(10, 5) }, - spans.GetOverlap(new Span(0, 15))); - // overlap with [20, 35) - Assert.Equal(new Span[] { new Span(30, 5) }, - spans.GetOverlap(new Span(20, 15))); - - // overlap with [0, 35) - Assert.Equal(new Span[] { new Span(10, 10), new Span(30, 5) }, - spans.GetOverlap(new Span(0, 35))); - // overlap with [15, 35) - Assert.Equal(new Span[] { new Span(15, 5), new Span(30, 5) }, - spans.GetOverlap(new Span(15, 20))); - // overlap with [15, 50) - Assert.Equal(new Span[] { new Span(15, 5), new Span(30, 10) }, - spans.GetOverlap(new Span(15, 35))); - // overlap with [0, 25) - Assert.Equal(new Span[] { new Span(10, 10) }, - spans.GetOverlap(new Span(0, 25))); - // overlap with [25, 45) - Assert.Equal(new Span[] { new Span(30, 10) }, - spans.GetOverlap(new Span(25, 20))); - // overlap with [0, 50) - Assert.Equal(new Span[] { new Span(10, 10), new Span(30, 10) }, - spans.GetOverlap(new Span(0, 50))); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestClipboard.cs b/src/InteractiveWindow/EditorTest/TestClipboard.cs deleted file mode 100644 index 5b0e8cd112868..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestClipboard.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Windows; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - internal sealed class TestClipboard : InteractiveWindowClipboard - { - private DataObject _data = null; - - internal void Clear() => _data = null; - - internal override bool ContainsData(string format) => _data?.GetData(format) != null; - - internal override object GetData(string format) => _data?.GetData(format); - - internal override bool ContainsText() => _data != null ? _data.ContainsText() : false; - - internal override string GetText() => _data?.GetText(); - - internal override void SetDataObject(object data, bool copy) => _data = (DataObject)data; - - internal override IDataObject GetDataObject() => _data; - } -} diff --git a/src/InteractiveWindow/EditorTest/TestContentTypeDefinition.cs b/src/InteractiveWindow/EditorTest/TestContentTypeDefinition.cs deleted file mode 100644 index 9629712d68a0e..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestContentTypeDefinition.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public sealed class TestContentTypeDefinition - { - public const string ContentTypeName = "InteractiveWindowTest"; - - [Export] - [Name(ContentTypeName)] - [BaseDefinition("code")] - public static readonly ContentTypeDefinition Definition; - } -} diff --git a/src/InteractiveWindow/EditorTest/TestInteractiveEngine.cs b/src/InteractiveWindow/EditorTest/TestInteractiveEngine.cs deleted file mode 100644 index 053697ceb0c05..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestInteractiveEngine.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading.Tasks; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - public sealed class TestInteractiveEngine : IInteractiveEvaluator - { - internal event EventHandler OnExecute; - - private readonly IContentType _contentType; - private IInteractiveWindow _currentWindow; - - public TestInteractiveEngine(IContentTypeRegistryService contentTypeRegistryService) - { - _contentType = contentTypeRegistryService.GetContentType(TestContentTypeDefinition.ContentTypeName); - } - - public IInteractiveWindow CurrentWindow - { - get - { - return _currentWindow; - } - - set - { - _currentWindow = value; - } - } - - public void Dispose() - { - } - - public Task InitializeAsync() - { - return Task.FromResult(ExecutionResult.Success); - } - - public Task ResetAsync(bool initialize = true) - { - return Task.FromResult(ExecutionResult.Success); - } - - public bool CanExecuteCode(string text) - { - return true; - } - - public Task ExecuteCodeAsync(string text) - { - OnExecute?.Invoke(this, text); - return Task.FromResult(ExecutionResult.Success); - } - - public string FormatClipboard() - { - return null; - } - - public void AbortExecution() - { - } - - public string GetConfiguration() - { - return "config"; - } - - public string GetPrompt() - { - return "> "; - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestSmartIndent.cs b/src/InteractiveWindow/EditorTest/TestSmartIndent.cs deleted file mode 100644 index 6f2f6cf92050f..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestSmartIndent.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - internal class TestSmartIndent : ISmartIndent - { - private readonly int[] _lineToIndentMap; - - public TestSmartIndent(params int[] lineToIndentMap) - { - _lineToIndentMap = lineToIndentMap; - } - - int? ISmartIndent.GetDesiredIndentation(ITextSnapshotLine line) - { - return _lineToIndentMap[line.LineNumber]; - } - - void IDisposable.Dispose() - { - } - } - - internal class DummySmartIndent : ISmartIndent - { - public static readonly ISmartIndent Instance = new DummySmartIndent(); - - private DummySmartIndent() - { - } - - int? ISmartIndent.GetDesiredIndentation(ITextSnapshotLine line) - { - return null; - } - - void IDisposable.Dispose() - { - } - } - - [Export(typeof(TestSmartIndentProvider))] - [Export(typeof(ISmartIndentProvider))] - [ContentType(InteractiveWindowEditorsFactoryService.ContentType)] - internal class TestSmartIndentProvider : ISmartIndentProvider - { - public ISmartIndent SmartIndent; - - ISmartIndent ISmartIndentProvider.CreateSmartIndent(ITextView textView) => SmartIndent ?? DummySmartIndent.Instance; - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/AssertEx.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/AssertEx.cs deleted file mode 100644 index 55f36d0a7b1bd..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/AssertEx.cs +++ /dev/null @@ -1,506 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Text; -using System.Xml.Linq; -using Microsoft.CodeAnalysis.Test.Utilities; -using Xunit; - -namespace Roslyn.Test.Utilities -{ - /// - /// Assert style type to deal with the lack of features in xUnit's Assert type - /// - public static class AssertEx - { - #region AssertEqualityComparer - - private class AssertEqualityComparer : IEqualityComparer - { - private static readonly IEqualityComparer s_instance = new AssertEqualityComparer(); - - private static bool CanBeNull() - { - var type = typeof(T); - return !type.GetTypeInfo().IsValueType || - (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); - } - - public static bool IsNull(T @object) - { - if (!CanBeNull()) - { - return false; - } - - return object.Equals(@object, default(T)); - } - - public static bool Equals(T left, T right) - { - return s_instance.Equals(left, right); - } - - bool IEqualityComparer.Equals(T x, T y) - { - if (CanBeNull()) - { - if (object.Equals(x, default(T))) - { - return object.Equals(y, default(T)); - } - - if (object.Equals(y, default(T))) - { - return false; - } - } - - if (x.GetType() != y.GetType()) - { - return false; - } - - var equatable = x as IEquatable; - if (equatable != null) - { - return equatable.Equals(y); - } - - var comparableT = x as IComparable; - if (comparableT != null) - { - return comparableT.CompareTo(y) == 0; - } - - var comparable = x as IComparable; - if (comparable != null) - { - return comparable.CompareTo(y) == 0; - } - - var enumerableX = x as IEnumerable; - var enumerableY = y as IEnumerable; - - if (enumerableX != null && enumerableY != null) - { - var enumeratorX = enumerableX.GetEnumerator(); - var enumeratorY = enumerableY.GetEnumerator(); - - while (true) - { - bool hasNextX = enumeratorX.MoveNext(); - bool hasNextY = enumeratorY.MoveNext(); - - if (!hasNextX || !hasNextY) - { - return hasNextX == hasNextY; - } - - if (!Equals(enumeratorX.Current, enumeratorY.Current)) - { - return false; - } - } - } - - return object.Equals(x, y); - } - - int IEqualityComparer.GetHashCode(T obj) - { - throw new NotImplementedException(); - } - } - - #endregion - - public static void AreEqual(T expected, T actual, string message = null, IEqualityComparer comparer = null) - { - if (ReferenceEquals(expected, actual)) - { - return; - } - - if (expected == null) - { - Fail("expected was null, but actual wasn't\r\n" + message); - } - else if (actual == null) - { - Fail("actual was null, but expected wasn't\r\n" + message); - } - else - { - if (!(comparer != null ? - comparer.Equals(expected, actual) : - AssertEqualityComparer.Equals(expected, actual))) - { - Fail("Expected and actual were different.\r\n" + - "Expected: " + expected + "\r\n" + - "Actual: " + actual + "\r\n" + - message); - } - } - } - - public static void Equal(ImmutableArray expected, IEnumerable actual, IEqualityComparer comparer = null, string message = null) - { - if (actual == null || expected.IsDefault) - { - Assert.True((actual == null) == expected.IsDefault, message); - } - else - { - Equal((IEnumerable)expected, actual, comparer, message); - } - } - - public static void Equal(IEnumerable expected, ImmutableArray actual, IEqualityComparer comparer = null, string message = null, string itemSeparator = null) - { - if (expected == null || actual.IsDefault) - { - Assert.True((expected == null) == actual.IsDefault, message); - } - else - { - Equal(expected, (IEnumerable)actual, comparer, message, itemSeparator); - } - } - - public static void Equal(ImmutableArray expected, ImmutableArray actual, IEqualityComparer comparer = null, string message = null, string itemSeparator = null) - { - Equal(expected, (IEnumerable)actual, comparer, message, itemSeparator); - } - - public static void Equal(IEnumerable expected, IEnumerable actual, IEqualityComparer comparer = null, string message = null, - string itemSeparator = null, Func itemInspector = null) - { - if (ReferenceEquals(expected, actual)) - { - return; - } - - if (expected == null) - { - Fail("expected was null, but actual wasn't\r\n" + message); - } - else if (actual == null) - { - Fail("actual was null, but expected wasn't\r\n" + message); - } - else if (!SequenceEqual(expected, actual, comparer)) - { - string assertMessage = GetAssertMessage(expected, actual, comparer, itemInspector, itemSeparator); - - if (message != null) - { - assertMessage = message + "\r\n" + assertMessage; - } - - Assert.True(false, assertMessage); - } - } - - private static bool SequenceEqual(IEnumerable expected, IEnumerable actual, IEqualityComparer comparer = null) - { - var enumerator1 = expected.GetEnumerator(); - var enumerator2 = actual.GetEnumerator(); - - while (true) - { - var hasNext1 = enumerator1.MoveNext(); - var hasNext2 = enumerator2.MoveNext(); - - if (hasNext1 != hasNext2) - { - return false; - } - - if (!hasNext1) - { - break; - } - - var value1 = enumerator1.Current; - var value2 = enumerator2.Current; - - if (!(comparer != null ? comparer.Equals(value1, value2) : AssertEqualityComparer.Equals(value1, value2))) - { - return false; - } - } - - return true; - } - - public static void SetEqual(IEnumerable expected, IEnumerable actual, IEqualityComparer comparer = null, string message = null, string itemSeparator = "\r\n") - { - var expectedSet = new HashSet(expected, comparer); - var result = expected.Count() == actual.Count() && expectedSet.SetEquals(actual); - if (!result) - { - if (string.IsNullOrEmpty(message)) - { - message = GetAssertMessage( - ToString(expected, itemSeparator), - ToString(actual, itemSeparator)); - } - - Assert.True(result, message); - } - } - - public static void SetEqual(IEnumerable actual, params T[] expected) - { - var expectedSet = new HashSet(expected); - Assert.True(expectedSet.SetEquals(actual), string.Format("Expected: {0}\nActual: {1}", ToString(expected), ToString(actual))); - } - - public static void None(IEnumerable actual, Func predicate) - { - var none = !actual.Any(predicate); - if (!none) - { - Assert.True(none, string.Format( - "Unexpected item found among existing items: {0}\nExisting items: {1}", - ToString(actual.First(predicate)), - ToString(actual))); - } - } - - public static void Any(IEnumerable actual, Func predicate) - { - var any = actual.Any(predicate); - Assert.True(any, string.Format("No expected item was found.\nExisting items: {0}", ToString(actual))); - } - - public static void All(IEnumerable actual, Func predicate) - { - var all = actual.All(predicate); - if (!all) - { - Assert.True(all, string.Format( - "Not all items satisfy condition:\n{0}", - ToString(actual.Where(i => !predicate(i))))); - } - } - - public static string ToString(object o) - { - return Convert.ToString(o); - } - - public static string ToString(IEnumerable list, string separator = ", ", Func itemInspector = null) - { - if (itemInspector == null) - { - itemInspector = i => Convert.ToString(i); - } - - return string.Join(separator, list.Select(itemInspector)); - } - - public static void Fail(string message) - { - Assert.False(true, message); - } - - public static void Fail(string format, params object[] args) - { - Assert.False(true, string.Format(format, args)); - } - - public static void NotNull(T @object, string message = null) - { - Assert.False(AssertEqualityComparer.IsNull(@object), message); - } - - // compares against a baseline - public static void AssertEqualToleratingWhitespaceDifferences( - string expected, - string actual, - bool escapeQuotes = true, - [CallerFilePath]string expectedValueSourcePath = null, - [CallerLineNumber]int expectedValueSourceLine = 0) - { - var normalizedExpected = NormalizeWhitespace(expected); - var normalizedActual = NormalizeWhitespace(actual); - - if (normalizedExpected != normalizedActual) - { - Assert.True(false, GetAssertMessage(expected, actual, escapeQuotes, expectedValueSourcePath, expectedValueSourceLine)); - } - } - - // compares two results (no baseline) - public static void AssertResultsEqual(string result1, string result2) - { - if (result1 != result2) - { - string message; - - if (DiffToolAvailable) - { - string file1 = Path.GetTempFileName(); - File.WriteAllText(file1, result1); - - string file2 = Path.GetTempFileName(); - File.WriteAllText(file2, result2); - - message = MakeDiffToolLink(file1, file2); - } - else - { - message = GetAssertMessage(result1, result2); - } - - Assert.True(false, message); - } - } - - public static void AssertContainsToleratingWhitespaceDifferences(string expectedSubString, string actualString) - { - expectedSubString = NormalizeWhitespace(expectedSubString); - actualString = NormalizeWhitespace(actualString); - Assert.Contains(expectedSubString, actualString, StringComparison.Ordinal); - } - - internal static string NormalizeWhitespace(string input) - { - var output = new StringBuilder(); - var inputLines = input.Split('\n', '\r'); - foreach (var line in inputLines) - { - var trimmedLine = line.Trim(); - if (trimmedLine.Length > 0) - { - if (!(trimmedLine[0] == '{' || trimmedLine[0] == '}')) - { - output.Append(" "); - } - - output.AppendLine(trimmedLine); - } - } - - return output.ToString(); - } - - public static string GetAssertMessage(string expected, string actual, bool escapeQuotes = false, string expectedValueSourcePath = null, int expectedValueSourceLine = 0) - { - return GetAssertMessage(DiffUtil.Lines(expected), DiffUtil.Lines(actual), escapeQuotes, expectedValueSourcePath, expectedValueSourceLine); - } - - public static string GetAssertMessage(IEnumerable expected, IEnumerable actual, bool escapeQuotes, string expectedValueSourcePath = null, int expectedValueSourceLine = 0) - { - Func itemInspector = escapeQuotes ? new Func(t => t.ToString().Replace("\"", "\"\"")) : null; - return GetAssertMessage(expected, actual, itemInspector: itemInspector, itemSeparator: "\r\n", expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); - } - - private static readonly string s_diffToolPath = Environment.GetEnvironmentVariable("ROSLYN_DIFFTOOL"); - - public static string GetAssertMessage( - IEnumerable expected, - IEnumerable actual, - IEqualityComparer comparer = null, - Func itemInspector = null, - string itemSeparator = null, - string expectedValueSourcePath = null, - int expectedValueSourceLine = 0) - { - if (itemInspector == null) - { - if (expected is IEnumerable) - { - itemInspector = b => $"0x{b:X2}"; - } - else - { - itemInspector = new Func(obj => (obj != null) ? obj.ToString() : ""); - } - } - - if (itemSeparator == null) - { - if (expected is IEnumerable) - { - itemSeparator = ", "; - } - else - { - itemSeparator = ",\r\n"; - } - } - - var expectedString = string.Join(itemSeparator, expected.Select(itemInspector)); - var actualString = string.Join(itemSeparator, actual.Select(itemInspector)); - - var message = new StringBuilder(); - message.AppendLine(); - message.AppendLine("Expected:"); - message.AppendLine(expectedString); - message.AppendLine("Actual:"); - message.AppendLine(actualString); - message.AppendLine("Differences:"); - message.AppendLine(DiffUtil.DiffReport(expected, actual, comparer, itemInspector, itemSeparator)); - - string link; - if (TryGenerateExpectedSourceFileAndGetDiffLink(actualString, expected.Count(), expectedValueSourcePath, expectedValueSourceLine, out link)) - { - message.AppendLine(link); - } - - return message.ToString(); - } - - internal static bool TryGenerateExpectedSourceFileAndGetDiffLink(string actualString, int expectedLineCount, string expectedValueSourcePath, int expectedValueSourceLine, out string link) - { - // add a link to a .cmd file that opens a diff tool: - if (DiffToolAvailable && expectedValueSourcePath != null && expectedValueSourceLine != 0) - { - var actualFile = Path.GetTempFileName(); - var testFileLines = File.ReadAllLines(expectedValueSourcePath); - - File.WriteAllLines(actualFile, testFileLines.Take(expectedValueSourceLine)); - File.AppendAllText(actualFile, actualString); - File.AppendAllLines(actualFile, testFileLines.Skip(expectedValueSourceLine + expectedLineCount)); - - link = MakeDiffToolLink(actualFile, expectedValueSourcePath); - - return true; - } - - link = null; - return false; - } - - internal static bool DiffToolAvailable => !string.IsNullOrEmpty(s_diffToolPath); - - internal static string MakeDiffToolLink(string actualFilePath, string expectedFilePath) - { - var compareCmd = Path.GetTempFileName() + ".cmd"; - File.WriteAllText(compareCmd, string.Format("\"{0}\" \"{1}\" \"{2}\"", s_diffToolPath, actualFilePath, expectedFilePath)); - - return "file://" + compareCmd; - } - - public static void Empty(IEnumerable items, string message = "") - { - // realize the list in case it can't be traversed twice via .Count()/.Any() and .Select() - var list = items.ToList(); - if (list.Count != 0) - { - Fail($"Expected 0 items but found {list.Count}: {message}\r\nItems:\r\n {string.Join("\r\n ", list)}"); - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/ConditionalFactAttribute.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/ConditionalFactAttribute.cs deleted file mode 100644 index 179ebf6bf3439..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/ConditionalFactAttribute.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Globalization; -using System.Text; -using Xunit; - -namespace Roslyn.Test.Utilities -{ - public class ConditionalFactAttribute : FactAttribute - { - public ConditionalFactAttribute(params Type[] skipConditions) - { - foreach (var skipCondition in skipConditions) - { - ExecutionCondition condition = (ExecutionCondition)Activator.CreateInstance(skipCondition); - if (condition.ShouldSkip) - { - Skip = condition.SkipReason; - break; - } - } - } - } - - public abstract class ExecutionCondition - { - public abstract bool ShouldSkip { get; } - public abstract string SkipReason { get; } - } - - public class x86 : ExecutionCondition - { - public override bool ShouldSkip => IntPtr.Size != 4; - - public override string SkipReason => "Target platform is not x86"; - } - - public class HasShiftJisDefaultEncoding : ExecutionCondition - { - public override bool ShouldSkip => Encoding.GetEncoding(0)?.CodePage != 932; - - public override string SkipReason => "OS default codepage is not Shift-JIS (932)."; - } - - public class IsEnglishLocal : ExecutionCondition - { - public override bool ShouldSkip => - !CultureInfo.CurrentUICulture.Name.StartsWith("en", StringComparison.OrdinalIgnoreCase) || - !CultureInfo.CurrentCulture.Name.StartsWith("en", StringComparison.OrdinalIgnoreCase); - - public override string SkipReason => "Current culture is not en"; - } - - public class IsRelease : ExecutionCondition - { -#if DEBUG - public override bool ShouldSkip => true; -#else - public override bool ShouldSkip => false; -#endif - - public override string SkipReason => "Not in release mode."; - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/DiffUtil.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/DiffUtil.cs deleted file mode 100644 index dd78b53f30999..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/DiffUtil.cs +++ /dev/null @@ -1,270 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; - -namespace Microsoft.CodeAnalysis.Test.Utilities -{ - public class DiffUtil - { - private enum EditKind - { - /// - /// No change. - /// - None = 0, - - /// - /// Node value was updated. - /// - Update = 1, - - /// - /// Node was inserted. - /// - Insert = 2, - - /// - /// Node was deleted. - /// - Delete = 3, - } - - private class LCS : LongestCommonSubsequence> - { - public static readonly LCS Default = new LCS(EqualityComparer.Default); - - private readonly IEqualityComparer _comparer; - - public LCS(IEqualityComparer comparer) - { - _comparer = comparer; - } - - protected override bool ItemsEqual(IList sequenceA, int indexA, IList sequenceB, int indexB) - { - return _comparer.Equals(sequenceA[indexA], sequenceB[indexB]); - } - - public IEnumerable CalculateDiff(IList sequenceA, IList sequenceB, Func toString) - { - foreach (var edit in GetEdits(sequenceA, sequenceA.Count, sequenceB, sequenceB.Count).Reverse()) - { - switch (edit.Kind) - { - case EditKind.Delete: - yield return "--> " + toString(sequenceA[edit.IndexA]); - break; - - case EditKind.Insert: - yield return "++> " + toString(sequenceB[edit.IndexB]); - break; - - case EditKind.Update: - yield return " " + toString(sequenceB[edit.IndexB]); - break; - } - } - } - } - - public static string DiffReport(IEnumerable expected, IEnumerable actual, IEqualityComparer comparer = null, Func toString = null, string separator = ",\r\n") - { - var lcs = (comparer != null) ? new LCS(comparer) : LCS.Default; - toString = toString ?? new Func(obj => obj.ToString()); - - IList expectedList = expected as IList ?? new List(expected); - IList actualList = actual as IList ?? new List(actual); - - return string.Join(separator, lcs.CalculateDiff(expectedList, actualList, toString)); - } - - private static readonly char[] s_lineSplitChars = new[] { '\r', '\n' }; - - public static string[] Lines(string s) - { - return s.Split(s_lineSplitChars, StringSplitOptions.RemoveEmptyEntries); - } - - public static string DiffReport(string expected, string actual) - { - var exlines = Lines(expected); - var aclines = Lines(actual); - return DiffReport(exlines, aclines, separator: "\r\n"); - } - - /// - /// Calculates Longest Common Subsequence. - /// - private abstract class LongestCommonSubsequence - { - protected struct Edit - { - public readonly EditKind Kind; - public readonly int IndexA; - public readonly int IndexB; - - internal Edit(EditKind kind, int indexA, int indexB) - { - this.Kind = kind; - this.IndexA = indexA; - this.IndexB = indexB; - } - } - - private const int DeleteCost = 1; - private const int InsertCost = 1; - private const int UpdateCost = 2; - - protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB); - - protected IEnumerable> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) - { - int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB); - int i = lengthA; - int j = lengthB; - - while (i != 0 && j != 0) - { - if (d[i, j] == d[i - 1, j] + DeleteCost) - { - i--; - } - else if (d[i, j] == d[i, j - 1] + InsertCost) - { - j--; - } - else - { - i--; - j--; - yield return new KeyValuePair(i, j); - } - } - } - - protected IEnumerable GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) - { - int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB); - int i = lengthA; - int j = lengthB; - - while (i != 0 && j != 0) - { - if (d[i, j] == d[i - 1, j] + DeleteCost) - { - i--; - yield return new Edit(EditKind.Delete, i, -1); - } - else if (d[i, j] == d[i, j - 1] + InsertCost) - { - j--; - yield return new Edit(EditKind.Insert, -1, j); - } - else - { - i--; - j--; - yield return new Edit(EditKind.Update, i, j); - } - } - - while (i > 0) - { - i--; - yield return new Edit(EditKind.Delete, i, -1); - } - - while (j > 0) - { - j--; - yield return new Edit(EditKind.Insert, -1, j); - } - } - - /// - /// Returns a distance [0..1] of the specified sequences. - /// The smaller distance the more of their elements match. - /// - /// - /// Returns a distance [0..1] of the specified sequences. - /// The smaller distance the more of their elements match. - /// - protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) - { - Debug.Assert(lengthA >= 0 && lengthB >= 0); - - if (lengthA == 0 || lengthB == 0) - { - return (lengthA == lengthB) ? 0.0 : 1.0; - } - - int lcsLength = 0; - foreach (var pair in GetMatchingPairs(sequenceA, lengthA, sequenceB, lengthB)) - { - lcsLength++; - } - - int max = Math.Max(lengthA, lengthB); - Debug.Assert(lcsLength <= max); - return 1.0 - (double)lcsLength / (double)max; - } - - /// - /// Calculates costs of all paths in an edit graph starting from vertex (0,0) and ending in vertex (lengthA, lengthB). - /// - /// - /// The edit graph for A and B has a vertex at each point in the grid (i,j), i in [0, lengthA] and j in [0, lengthB]. - /// - /// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph. - /// Horizontal edges connect each vertex to its right neighbor. - /// Vertical edges connect each vertex to the neighbor below it. - /// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if (sequenceA[i-1],sequenceB[j-1]) is true. - /// - /// Editing starts with S = []. - /// Move along horizontal edge (i-1,j)-(i,j) represents the fact that sequenceA[i-1] is not added to S. - /// Move along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1] to S. - /// Move along diagonal edge (i-1,j-1)-(i,j) represents an addition of sequenceB[j-1] to S via an acceptable - /// change of sequenceA[i-1] to sequenceB[j-1]. - /// - /// In every vertex the cheapest outgoing edge is selected. - /// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common subsequence. - /// - private int[,] ComputeCostMatrix(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB) - { - var la = lengthA + 1; - var lb = lengthB + 1; - - // TODO: Optimization possible: O(ND) time, O(N) space - // EUGENE W. MYERS: An O(ND) Difference Algorithm and Its Variations - var d = new int[la, lb]; - - d[0, 0] = 0; - for (int i = 1; i <= lengthA; i++) - { - d[i, 0] = d[i - 1, 0] + DeleteCost; - } - - for (int j = 1; j <= lengthB; j++) - { - d[0, j] = d[0, j - 1] + InsertCost; - } - - for (int i = 1; i <= lengthA; i++) - { - for (int j = 1; j <= lengthB; j++) - { - int m1 = d[i - 1, j - 1] + (ItemsEqual(sequenceA, i - 1, sequenceB, j - 1) ? 0 : UpdateCost); - int m2 = d[i - 1, j] + DeleteCost; - int m3 = d[i, j - 1] + InsertCost; - d[i, j] = Math.Min(Math.Min(m1, m2), m3); - } - } - - return d; - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityTesting.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityTesting.cs deleted file mode 100644 index 056e83725c0bd..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityTesting.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace Microsoft.CodeAnalysis.Test.Utilities -{ - /// - /// Helpers for testing equality APIs. - /// Gives us more control than calling Assert.Equals. - /// - public static class EqualityTesting - { - public static void AssertEqual(IEquatable x, IEquatable y) - { - Assert.True(x.Equals(y)); - Assert.True(((object)x).Equals(y)); - Assert.Equal(x.GetHashCode(), y.GetHashCode()); - } - - public static void AssertNotEqual(IEquatable x, IEquatable y) - { - Assert.False(x.Equals(y)); - Assert.False(((object)x).Equals(y)); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUnit.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUnit.cs deleted file mode 100644 index 435e8d1f26744..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUnit.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Roslyn.Test.Utilities -{ - public static class EqualityUnit - { - public static EqualityUnit Create(T value) - { - return new EqualityUnit(value); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUnit`1.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUnit`1.cs deleted file mode 100644 index 1879f05eda210..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUnit`1.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; - -namespace Roslyn.Test.Utilities -{ - public sealed class EqualityUnit - { - private static readonly ReadOnlyCollection s_emptyCollection = new ReadOnlyCollection(new T[] { }); - - public readonly T Value; - public readonly ReadOnlyCollection EqualValues; - public readonly ReadOnlyCollection NotEqualValues; - public IEnumerable AllValues - { - get { return Enumerable.Repeat(Value, 1).Concat(EqualValues).Concat(NotEqualValues); } - } - - public EqualityUnit(T value) - { - Value = value; - EqualValues = s_emptyCollection; - NotEqualValues = s_emptyCollection; - } - - public EqualityUnit( - T value, - ReadOnlyCollection equalValues, - ReadOnlyCollection notEqualValues) - { - Value = value; - EqualValues = equalValues; - NotEqualValues = notEqualValues; - } - - public EqualityUnit WithEqualValues(params T[] equalValues) - { - return new EqualityUnit( - Value, - EqualValues.Concat(equalValues).ToList().AsReadOnly(), - NotEqualValues); - } - - public EqualityUnit WithNotEqualValues(params T[] notEqualValues) - { - return new EqualityUnit( - Value, - EqualValues, - NotEqualValues.Concat(notEqualValues).ToList().AsReadOnly()); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUtil.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUtil.cs deleted file mode 100644 index c9442c173a124..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUtil.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Roslyn.Test.Utilities -{ - public static class EqualityUtil - { - public static void RunAll( - Func compEqualsOperator, - Func compNotEqualsOperator, - params EqualityUnit[] values) - { - var util = new EqualityUtil(values, compEqualsOperator, compNotEqualsOperator); - util.RunAll(); - } - - public static void RunAll(EqualityUnit unit, bool checkIEquatable = true) - { - RunAll(checkIEquatable, new[] { unit }); - } - - public static void RunAll(params EqualityUnit[] values) - { - RunAll(checkIEquatable: true, values: values); - } - - public static void RunAll(bool checkIEquatable, params EqualityUnit[] values) - { - var util = new EqualityUtil(values); - util.RunAll(checkIEquatable); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUtil`1.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUtil`1.cs deleted file mode 100644 index b3107f59cec4d..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/EqualityUtil`1.cs +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using Xunit; - -namespace Roslyn.Test.Utilities -{ - /// - /// Base class which does a lot of the boiler plate work for testing that the equality pattern - /// is properly implemented in objects - /// - public sealed class EqualityUtil - { - private readonly ReadOnlyCollection> _equalityUnits; - private readonly Func _compareWithEqualityOperator; - private readonly Func _compareWithInequalityOperator; - - public EqualityUtil( - IEnumerable> equalityUnits, - Func compEquality = null, - Func compInequality = null) - { - _equalityUnits = equalityUnits.ToList().AsReadOnly(); - _compareWithEqualityOperator = compEquality; - _compareWithInequalityOperator = compInequality; - } - - public void RunAll(bool checkIEquatable = true) - { - if (_compareWithEqualityOperator != null) - { - EqualityOperator1(); - EqualityOperator2(); - } - - if (_compareWithInequalityOperator != null) - { - InequalityOperator1(); - InequalityOperator2(); - } - - if (checkIEquatable) - { - ImplementsIEquatable(); - } - - ObjectEquals1(); - ObjectEquals2(); - ObjectEquals3(); - GetHashCode1(); - - if (checkIEquatable) - { - EquatableEquals1(); - EquatableEquals2(); - } - } - - private void EqualityOperator1() - { - foreach (var unit in _equalityUnits) - { - foreach (var value in unit.EqualValues) - { - Assert.True(_compareWithEqualityOperator(unit.Value, value)); - Assert.True(_compareWithEqualityOperator(value, unit.Value)); - } - - foreach (var value in unit.NotEqualValues) - { - Assert.False(_compareWithEqualityOperator(unit.Value, value)); - Assert.False(_compareWithEqualityOperator(value, unit.Value)); - } - } - } - - private void EqualityOperator2() - { - if (typeof(T).GetTypeInfo().IsValueType) - { - return; - } - - foreach (var value in _equalityUnits.SelectMany(x => x.AllValues)) - { - Assert.False(_compareWithEqualityOperator(default(T), value)); - Assert.False(_compareWithEqualityOperator(value, default(T))); - } - } - - private void InequalityOperator1() - { - foreach (var unit in _equalityUnits) - { - foreach (var value in unit.EqualValues) - { - Assert.False(_compareWithInequalityOperator(unit.Value, value)); - Assert.False(_compareWithInequalityOperator(value, unit.Value)); - } - - foreach (var value in unit.NotEqualValues) - { - Assert.True(_compareWithInequalityOperator(unit.Value, value)); - Assert.True(_compareWithInequalityOperator(value, unit.Value)); - } - } - } - - private void InequalityOperator2() - { - if (typeof(T).GetTypeInfo().IsValueType) - { - return; - } - - foreach (var value in _equalityUnits.SelectMany(x => x.AllValues)) - { - Assert.True(_compareWithInequalityOperator(default(T), value)); - Assert.True(_compareWithInequalityOperator(value, default(T))); - } - } - - private void ImplementsIEquatable() - { - var type = typeof(T); - var targetType = typeof(IEquatable); - Assert.True(type.GetTypeInfo().ImplementedInterfaces.Contains(targetType)); - } - - private void ObjectEquals1() - { - foreach (var unit in _equalityUnits) - { - var unitValue = unit.Value; - foreach (var value in unit.EqualValues) - { - Assert.True(value.Equals(unitValue)); - Assert.True(unitValue.Equals(value)); - } - } - } - - /// - /// Comparison with Null should be false for reference types - /// - private void ObjectEquals2() - { - if (typeof(T).GetTypeInfo().IsValueType) - { - return; - } - - var allValues = _equalityUnits.SelectMany(x => x.AllValues); - foreach (var value in allValues) - { - Assert.NotNull(value); - } - } - - /// - /// Passing a value of a different type should just return false - /// - private void ObjectEquals3() - { - var allValues = _equalityUnits.SelectMany(x => x.AllValues); - foreach (var value in allValues) - { - Assert.False(value.Equals((object)42)); - } - } - - private void GetHashCode1() - { - foreach (var unit in _equalityUnits) - { - foreach (var value in unit.EqualValues) - { - Assert.Equal(value.GetHashCode(), unit.Value.GetHashCode()); - } - } - } - - private void EquatableEquals1() - { - foreach (var unit in _equalityUnits) - { - var equatableUnit = (IEquatable)unit.Value; - foreach (var value in unit.EqualValues) - { - Assert.True(equatableUnit.Equals(value)); - var equatableValue = (IEquatable)value; - Assert.True(equatableValue.Equals(unit.Value)); - } - - foreach (var value in unit.NotEqualValues) - { - Assert.False(equatableUnit.Equals(value)); - var equatableValue = (IEquatable)value; - Assert.False(equatableValue.Equals(unit.Value)); - } - } - } - - /// - /// If T is a reference type, null should return false in all cases - /// - private void EquatableEquals2() - { - if (typeof(T).GetTypeInfo().IsValueType) - { - return; - } - - foreach (var cur in _equalityUnits.SelectMany(x => x.AllValues)) - { - var value = (IEquatable)cur; - Assert.NotNull(value); - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/TestExceptionUtilities.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/TestExceptionUtilities.cs deleted file mode 100644 index 3dcb9ef718e2e..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/TestExceptionUtilities.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Microsoft.CodeAnalysis.Test.Utilities -{ - public static class TestExceptionUtilities - { - public static InvalidOperationException UnexpectedValue(object o) - { - string output = String.Format("Unexpected value '{0}' of type '{1}'", o, (o != null) ? o.GetType().FullName : ""); - System.Diagnostics.Debug.Fail(output); - return new InvalidOperationException(output); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/WorkItemAttribute.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Assert/WorkItemAttribute.cs deleted file mode 100644 index 56a5f53ad4712..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Assert/WorkItemAttribute.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Roslyn.Test.Utilities -{ - /// - /// Used to tag test methods or types which are created for a given WorkItem - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] - public sealed class WorkItemAttribute : Attribute - { - private readonly int _id; - private readonly string _description; - - public int Id - { - get { return _id; } - } - - public string Description - { - get { return _description; } - } - - public WorkItemAttribute(int id, string description) - { - _id = id; - _description = description; - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Async/AsynchronousOperationBlocker.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Async/AsynchronousOperationBlocker.cs deleted file mode 100644 index f2363ac1f8e8d..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Async/AsynchronousOperationBlocker.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; - -namespace Roslyn.Test.Utilities -{ - public sealed class AsynchronousOperationBlocker : IDisposable - { - private readonly ManualResetEvent _waitHandle; - private readonly object _lockObj; - private bool _blocking; - private bool _disposed; - - public AsynchronousOperationBlocker() - { - _waitHandle = new ManualResetEvent(false); - _lockObj = new object(); - _blocking = true; - } - - public bool IsBlockingOperations - { - get - { - lock (_lockObj) - { - return _blocking; - } - } - - private set - { - lock (_lockObj) - { - if (_blocking == value) - { - return; - } - - _blocking = value; - if (!_disposed) - { - if (_blocking) - { - _waitHandle.Reset(); - } - else - { - _waitHandle.Set(); - } - } - } - } - } - - public void BlockOperations() - { - this.IsBlockingOperations = true; - } - - public void UnblockOperations() - { - this.IsBlockingOperations = false; - } - - public bool WaitIfBlocked(TimeSpan timeout) - { - if (_disposed) - { - Environment.FailFast("Badness"); - } - - return _waitHandle.WaitOne(timeout); - } - - public void Dispose() - { - if (!_disposed) - { - _disposed = true; - _waitHandle.Dispose(); - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Async/Checkpoint.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Async/Checkpoint.cs deleted file mode 100644 index 25ba0438559b4..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Async/Checkpoint.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Roslyn.Test.Utilities -{ - public class Checkpoint - { - private readonly TaskCompletionSource _tcs = new TaskCompletionSource(); - - public Task Task => _tcs.Task; - - public void Release() => _tcs.SetResult(null); - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Async/WaitHelper.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Async/WaitHelper.cs deleted file mode 100644 index ffa3a2c769f70..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Async/WaitHelper.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Threading; - -namespace Roslyn.Test.Utilities -{ - public static class WaitHelper - { - public static void WaitForDispatchedOperationsToComplete(DispatcherPriority priority) - { - Action action = delegate { }; - new FrameworkElement().Dispatcher.Invoke(action, priority); - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Contract.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Contract.cs deleted file mode 100644 index e33d4a7579305..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Contract.cs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; - -namespace Roslyn.Utilities -{ - internal static class Contract - { - /// - /// Equivalent to Debug.Assert. - /// - /// DevDiv 867813 covers removing this completely at a future date - /// - [Conditional("DEBUG")] - [DebuggerHidden] - public static void Requires(bool condition, string message = null) - { - Assert(condition, message); - } - - /// - /// Equivalent to Debug.Assert. - /// - /// DevDiv 867813 covers removing this completely at a future date - /// - [Conditional("DEBUG")] - [DebuggerHidden] - public static void Assert(bool condition, string message = null) - { - if (condition) - { - return; - } - - if (string.IsNullOrEmpty(message)) - { - Debug.Assert(condition); - } - else - { - Debug.Assert(condition, message); - } - } - - /// - /// Equivalent to Debug.Assert. - /// - /// DevDiv 867813 covers removing this completely at a future date - /// - [Conditional("DEBUG")] - public static void Assume(bool condition, string message = null) - { - if (string.IsNullOrEmpty(message)) - { - Debug.Assert(condition); - } - else - { - Debug.Assert(condition, message); - } - } - - /// - /// Throws a non-accessible exception if the provided value is null. This method executes in - /// all builds - /// - public static void ThrowIfNull(T value, string message = null) where T : class - { - if (value == null) - { - message = message ?? "Unexpected Null"; - Fail(message); - } - } - - /// - /// Throws a non-accessible exception if the provided value is false. This method executes - /// in all builds - /// - public static void ThrowIfFalse(bool condition, string message = null) - { - if (!condition) - { - message = message ?? "Unexpected false"; - Fail(message); - } - } - - /// - /// Throws a non-accessible exception if the provided value is true. This method executes in - /// all builds. - /// - public static void ThrowIfTrue(bool condition, string message = null) - { - if (condition) - { - message = message ?? "Unexpected true"; - Fail(message); - } - } - - [DebuggerHidden] - public static void Fail(string message = "Unexpected") - { - throw new InvalidOperationException(message); - } - - [DebuggerHidden] - public static T FailWithReturn(string message = "Unexpected") - { - throw new InvalidOperationException(message); - } - - public static void InvalidEnumValue(T value) - { - Fail(string.Format("Invalid Enumeration value {0}", value)); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ConditionalWpfFactAttribute.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ConditionalWpfFactAttribute.cs deleted file mode 100644 index 96ef35fdd9f70..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ConditionalWpfFactAttribute.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Roslyn.Test.Utilities -{ - public class ConditionalWpfFactAttribute : WpfFactAttribute - { - public ConditionalWpfFactAttribute(Type skipCondition) - { - var condition = Activator.CreateInstance(skipCondition) as ExecutionCondition; - - if (condition.ShouldSkip) - { - Skip = condition.SkipReason; - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ForegroundThreadAffinitizedObject.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ForegroundThreadAffinitizedObject.cs deleted file mode 100644 index b0954ea30232e..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ForegroundThreadAffinitizedObject.cs +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Threading; -using Microsoft.CodeAnalysis.Utilities; -using Roslyn.Utilities; -using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind; - -namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities -{ - internal sealed class ForegroundThreadData - { - internal readonly Thread Thread; - internal readonly TaskScheduler TaskScheduler; - internal readonly ForegroundThreadDataKind Kind; - - internal ForegroundThreadData(Thread thread, TaskScheduler taskScheduler, ForegroundThreadDataKind kind) - { - Thread = thread; - TaskScheduler = taskScheduler; - Kind = kind; - } - - /// - /// Creates the default ForegroundThreadData assuming that the current thread is the UI thread. - /// - /// The ForegroundThreadDataKind to fall back to if a UI thread cannot be found - /// default ForegroundThreadData values - internal static ForegroundThreadData CreateDefault(ForegroundThreadDataKind defaultKind) - { - var kind = ForegroundThreadDataInfo.CreateDefault(defaultKind); - - // None of the work posted to the foregroundTaskScheduler should block pending keyboard/mouse input from the user. - // So instead of using the default priority which is above user input, we use Background priority which is 1 level - // below user input. - var taskScheduler = new SynchronizationContextTaskScheduler(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher, DispatcherPriority.Background)); - - return new ForegroundThreadData(Thread.CurrentThread, taskScheduler, kind); - } - } - - /// - /// Base class that allows some helpers for detecting whether we're on the main WPF foreground thread, or - /// a background thread. It also allows scheduling work to the foreground thread at below input priority. - /// - internal class ForegroundThreadAffinitizedObject - { - private static readonly ForegroundThreadData s_fallbackForegroundThreadData; - private static ForegroundThreadData s_currentForegroundThreadData; - private readonly ForegroundThreadData _foregroundThreadData; - - internal static ForegroundThreadData CurrentForegroundThreadData - { - get - { - return s_currentForegroundThreadData ?? s_fallbackForegroundThreadData; - } - - set - { - s_currentForegroundThreadData = value; - ForegroundThreadDataInfo.SetCurrentForegroundThreadDataKind(s_currentForegroundThreadData?.Kind); - } - } - - internal ForegroundThreadData ForegroundThreadData - { - get { return _foregroundThreadData; } - } - - internal Thread ForegroundThread - { - get { return _foregroundThreadData.Thread; } - } - - internal TaskScheduler ForegroundTaskScheduler - { - get { return _foregroundThreadData.TaskScheduler; } - } - - // HACK: This is a dangerous way of establishing the 'foreground' thread affinity of an - // AppDomain. This method should be deleted in favor of forcing derivations of this type - // to either explicitly inherit WPF Dispatcher thread or provide an explicit thread - // they believe to be the foreground. - static ForegroundThreadAffinitizedObject() - { - s_fallbackForegroundThreadData = ForegroundThreadData.CreateDefault(Unknown); - } - - public ForegroundThreadAffinitizedObject(ForegroundThreadData foregroundThreadData = null, bool assertIsForeground = false) - { - _foregroundThreadData = foregroundThreadData ?? CurrentForegroundThreadData; - - // For sanity's sake, ensure that our idea of "foreground" is the same as WPF's - Contract.ThrowIfFalse(Application.Current == null || Application.Current.Dispatcher.Thread == ForegroundThread); - - // ForegroundThreadAffinitizedObject might not necessarily be created on a foreground thread. - // AssertIsForeground here only if the object must be created on a foreground thread. - if (assertIsForeground) - { - AssertIsForeground(); - } - } - - public bool IsForeground() - { - return Thread.CurrentThread == ForegroundThread; - } - - /// - /// Ensure this is a supported scheduling context like Wpf or explicit STA scheduler. - /// - /// - public bool IsValid() - { - return _foregroundThreadData.Kind != Unknown; - } - - public void AssertIsForeground() - { - Contract.ThrowIfFalse(IsForeground()); - } - - public void AssertIsBackground() - { - Contract.ThrowIfTrue(IsForeground()); - } - - /// - /// A helpful marker method that can be used by deriving classes to indicate that a - /// method can be called from any thread and is not foreground or background affinitized. - /// This is useful so that every method in deriving class can have some sort of marker - /// on each method stating the threading constraints (FG-only/BG-only/Any-thread). - /// - public void ThisCanBeCalledOnAnyThread() - { - // Does nothing. - } - - public Task InvokeBelowInputPriority(Action action, CancellationToken cancellationToken = default(CancellationToken)) - { - if (IsForeground() && !IsInputPending()) - { - // Optimize to inline the action if we're already on the foreground thread - // and there's no pending user input. - action(); - - return SpecializedTasks.EmptyTask; - } - else - { - return Task.Factory.SafeStartNew(action, cancellationToken, ForegroundTaskScheduler); - } - } - - /// - /// Returns true if any keyboard or mouse button input is pending on the message queue. - /// - protected bool IsInputPending() - { - // The return value of GetQueueStatus is HIWORD:LOWORD. - // A non-zero value in HIWORD indicates some input message in the queue. - uint result = NativeMethods.GetQueueStatus(NativeMethods.QS_INPUT); - - const uint InputMask = NativeMethods.QS_INPUT | (NativeMethods.QS_INPUT << 16); - return (result & InputMask) != 0; - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ForegroundThreadDataKind.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ForegroundThreadDataKind.cs deleted file mode 100644 index 2c4d204b92fac..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/ForegroundThreadDataKind.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Threading; -using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind; - -namespace Microsoft.CodeAnalysis.Utilities -{ - internal enum ForegroundThreadDataKind - { - Wpf, - WinForms, - StaUnitTest, - JoinableTask, - ForcedByPackageInitialize, - Unknown - } - - internal static class ForegroundThreadDataInfo - { - private static readonly ForegroundThreadDataKind s_fallbackForegroundThreadDataKind; - private static ForegroundThreadDataKind? s_currentForegroundThreadDataKind; - - static ForegroundThreadDataInfo() - { - s_fallbackForegroundThreadDataKind = CreateDefault(Unknown); - } - - internal static ForegroundThreadDataKind CreateDefault(ForegroundThreadDataKind defaultKind) - { - var syncConextTypeName = SynchronizationContext.Current?.GetType().FullName; - - switch (syncConextTypeName) - { - case "System.Windows.Threading.DispatcherSynchronizationContext": - - return Wpf; - - case "Microsoft.VisualStudio.Threading.JoinableTask+JoinableTaskSynchronizationContext": - - return JoinableTask; - - case "System.Windows.Forms.WindowsFormsSynchronizationContext": - - return WinForms; - - default: - - return defaultKind; - } - } - - internal static ForegroundThreadDataKind CurrentForegroundThreadDataKind - { - get { return s_currentForegroundThreadDataKind ?? s_fallbackForegroundThreadDataKind; } - } - - internal static void SetCurrentForegroundThreadDataKind(ForegroundThreadDataKind? kind) - { - s_currentForegroundThreadDataKind = kind; - } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/NativeMethods.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/NativeMethods.cs deleted file mode 100644 index ca454da6ae0a4..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/NativeMethods.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Runtime.InteropServices; - -namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities -{ - internal static class NativeMethods - { - internal const uint MWMO_INPUTAVAILABLE = 0x0004; - - internal const uint - QS_KEY = 0x0001, - QS_MOUSEMOVE = 0x0002, - QS_MOUSEBUTTON = 0x0004, - QS_POSTMESSAGE = 0x0008, - QS_TIMER = 0x0010, - QS_PAINT = 0x0020, - QS_SENDMESSAGE = 0x0040, - QS_HOTKEY = 0x0080, - QS_ALLPOSTMESSAGE = 0x0100, - QS_MOUSE = QS_MOUSEMOVE | QS_MOUSEBUTTON, - QS_INPUT = QS_MOUSE | QS_KEY, - QS_ALLEVENTS = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY, - QS_ALLINPUT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE, - QS_EVENT = 0x2000; - - [DllImport("user32.dll")] - internal static extern uint GetQueueStatus(uint flags); - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SemaphoreSlimExtensions.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SemaphoreSlimExtensions.cs deleted file mode 100644 index 494a0849320db..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SemaphoreSlimExtensions.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; -using System.Threading.Tasks; - -namespace Roslyn.Utilities -{ - internal static class SemaphoreSlimExtensions - { - public static SemaphoreDisposer DisposableWait(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default(CancellationToken)) - { - semaphore.Wait(cancellationToken); - return new SemaphoreDisposer(semaphore); - } - - public async static Task DisposableWaitAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default(CancellationToken)) - { - await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - return new SemaphoreDisposer(semaphore); - } - - internal struct SemaphoreDisposer : IDisposable - { - private readonly SemaphoreSlim _semaphore; - - public SemaphoreDisposer(SemaphoreSlim semaphore) - { - _semaphore = semaphore; - } - - public void Dispose() - { - _semaphore.Release(); - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SpecializedTasks.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SpecializedTasks.cs deleted file mode 100644 index 62ada95714628..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SpecializedTasks.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; - -namespace Roslyn.Utilities -{ - internal static class SpecializedTasks - { - public static readonly Task True = Task.FromResult(true); - public static readonly Task False = Task.FromResult(false); - public static readonly Task EmptyTask = Empty.Default; - - public static Task Default() - { - return Empty.Default; - } - - public static Task DefaultOrResult(T value) - { - if (EqualityComparer.Default.Equals(value, default(T))) - { - return Default(); - } - - return Task.FromResult(value); - } - - public static Task> EmptyImmutableArray() - { - return Empty.EmptyImmutableArray; - } - - public static Task> EmptyEnumerable() - { - return Empty.EmptyEnumerable; - } - - public static Task FromResult(T t) where T : class - { - return FromResultCache.FromResult(t); - } - - private static class Empty - { - public static readonly Task Default = Task.FromResult(default(T)); - public static readonly Task> EmptyEnumerable = Task.FromResult>(Array.Empty()); - public static readonly Task> EmptyImmutableArray = Task.FromResult(ImmutableArray.Empty); - } - - private static class FromResultCache where T : class - { - private static readonly ConditionalWeakTable> s_fromResultCache = new ConditionalWeakTable>(); - private static readonly ConditionalWeakTable>.CreateValueCallback s_taskCreationCallback = Task.FromResult; - - public static Task FromResult(T t) - { - return s_fromResultCache.GetValue(t, s_taskCreationCallback); - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/StaTaskScheduler.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/StaTaskScheduler.cs deleted file mode 100644 index 57d9f522246ad..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/StaTaskScheduler.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -// ParallelExtensionsExtras: https://code.msdn.microsoft.com/ParExtSamples - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace Roslyn.Test.Utilities -{ - /// Provides a scheduler that uses STA threads. - public sealed class StaTaskScheduler : TaskScheduler, IDisposable - { - /// Gets a StaTaskScheduler for the current AppDomain. - /// We use a count of 1, because the editor ends up re-using - /// instances between tests, so we need to always use the same thread for our Sta tests. - public static StaTaskScheduler DefaultSta { get; } = new StaTaskScheduler(1); - - /// Stores the queued tasks to be executed by our pool of STA threads. - private BlockingCollection _tasks; - - /// The STA threads used by the scheduler. - private readonly ImmutableArray _threads; - - public ImmutableArray Threads => _threads; - - /// Initializes a new instance of the StaTaskScheduler class with the specified concurrency level. - /// The number of threads that should be created and used by this scheduler. - public StaTaskScheduler(int numberOfThreads) - { - // Validate arguments - if (numberOfThreads < 1) - throw new ArgumentOutOfRangeException(nameof(numberOfThreads)); - - // Initialize the tasks collection - _tasks = new BlockingCollection(); - - // Create the threads to be used by this scheduler - _threads = Enumerable.Range(0, numberOfThreads).Select(i => - { - var thread = new Thread(() => - { - // Continually get the next task and try to execute it. - // This will continue until the scheduler is disposed and no more tasks remain. - foreach (var t in _tasks.GetConsumingEnumerable()) - { - if (!TryExecuteTask(t)) - { - System.Diagnostics.Debug.Assert(t.IsCompleted, "Can't run, not completed"); - } - } - }); - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - return thread; - }).ToImmutableArray(); - - // Start all of the threads - foreach (var thread in _threads) - { - thread.Start(); - } - } - - /// Queues a Task to be executed by this scheduler. - /// The task to be executed. - protected override void QueueTask(Task task) - { - // Push it into the blocking collection of tasks - _tasks.Add(task); - } - - /// Provides a list of the scheduled tasks for the debugger to consume. - /// An enumerable of all tasks currently scheduled. - protected override IEnumerable GetScheduledTasks() - { - // Serialize the contents of the blocking collection of tasks for the debugger - return _tasks.ToArray(); - } - - /// Determines whether a Task may be inlined. - /// The task to be executed. - /// Whether the task was previously queued. - /// true if the task was successfully inlined; otherwise, false. - protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) - { - // Try to inline if the current thread is STA - return - Thread.CurrentThread.GetApartmentState() == ApartmentState.STA && - TryExecuteTask(task); - } - - /// Gets the maximum concurrency level supported by this scheduler. - public override int MaximumConcurrencyLevel - { - get - { - return _threads.Length; - } - } - - /// - /// Cleans up the scheduler by indicating that no more tasks will be queued. - /// This method blocks until all threads successfully shutdown. - /// - public void Dispose() - { - if (_tasks != null) - { - // Indicate that no new tasks will be coming in - _tasks.CompleteAdding(); - - // Wait for all threads to finish processing tasks - foreach (var thread in _threads) - thread.Join(); - - // Cleanup - _tasks.Dispose(); - _tasks = null; - } - } - - public bool IsAnyQueued() - { - if (_threads.Length != 1 || _threads[0] != Thread.CurrentThread) - { - throw new InvalidOperationException("Operation invalid in this context"); - } - - return _tasks.Count > 0; - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SynchronizationContextTaskScheduler.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SynchronizationContextTaskScheduler.cs deleted file mode 100644 index f9e746a31a121..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/SynchronizationContextTaskScheduler.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities -{ - // Based on CoreCLR's implementation of the TaskScheduler they return from TaskScheduler.FromCurrentSynchronizationContext - internal class SynchronizationContextTaskScheduler : TaskScheduler - { - private readonly SendOrPostCallback _postCallback; - private readonly SynchronizationContext _synchronizationContext; - - internal SynchronizationContextTaskScheduler(SynchronizationContext synchronizationContext) - { - if (synchronizationContext == null) - throw new ArgumentNullException(nameof(synchronizationContext)); - - _postCallback = new SendOrPostCallback(PostCallback); - _synchronizationContext = synchronizationContext; - } - - public override Int32 MaximumConcurrencyLevel - { - get { return 1; } - } - - protected override void QueueTask(Task task) - { - _synchronizationContext.Post(_postCallback, task); - } - protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) - { - if (SynchronizationContext.Current == _synchronizationContext) - { - return TryExecuteTask(task); - } - - return false; - } - - protected override IEnumerable GetScheduledTasks() - { - return null; - } - - private void PostCallback(object obj) - { - TryExecuteTask((Task)obj); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/TaskExtensions.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/TaskExtensions.cs deleted file mode 100644 index 4073c5c051e4e..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/TaskExtensions.cs +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Utilities; -using Microsoft.VisualStudio.InteractiveWindow; - -namespace Roslyn.Utilities -{ - [SuppressMessage("ApiDesign", "CA1068", Justification = "Matching TPL Signatures")] - internal static partial class TaskExtensions - { - public static T WaitAndGetResult(this Task task, CancellationToken cancellationToken) - { -#if DEBUG - var threadKind = ForegroundThreadDataInfo.CurrentForegroundThreadDataKind; - if (threadKind == ForegroundThreadDataKind.Unknown) - { - // If you hit this when running tests then your code is in error. WaitAndGetResult - // should only be called from a foreground thread. There are a few ways you may - // want to fix this. - // - // First, if you're actually calling this directly *in test code* then you could - // either: - // - // 1) Mark the test with [WpfFact]. This is not preferred, and should only be - // when testing an actual UI feature (like command handlers). - // 2) Make the test actually async (preferred). - // - // If you are calling WaitAndGetResult from product code, then that code must - // be a foreground thread (i.e. a command handler). It cannot be from a threadpool - // thread *ever*. - throw new InvalidOperationException($"{nameof(WaitAndGetResult)} can only be called from a 'foreground' thread."); - } -#endif - - return WaitAndGetResult_CanCallOnBackground(task, cancellationToken); - } - - // Only call this *extremely* special situations. This will synchronously block a threadpool - // thread. In the future we are going ot be removing this and disallowing its use. - public static T WaitAndGetResult_CanCallOnBackground(this Task task, CancellationToken cancellationToken) - { - task.Wait(cancellationToken); - return task.Result; - } - - // NOTE(cyrusn): Once we switch over to .Net 4.5 we can make our SafeContinueWith overloads - // simply call into task.ContinueWith(..., TaskContinuationOptions.LazyCancellation, ...) as - // that will have the semantics that we want. From the TPL guys: - // - // In this situation: -#if false - Task A = Task.Run(...); - Task B = A.ContinueWith(..., cancellationToken); - Task C = B.ContinueWith(...); -#endif - // If "cancellationToken" is signaled, B completes immediately (if it has not yet started). - // Which means that C can start before A completes, which would seem to violate the rules of - // the dependency chain. - // - // We've added TaskContinuationOptions.LazyCancellation option to signify "this continuation - // will not complete due to cancellation until its antecedent has completed". We considered - // simply changing the default underlying behavior, but rejected that idea because there was - // a good chance that existing users had already drawn a dependency on the current behavior. - - public static Task SafeContinueWith( - this Task task, - Action continuationAction, - CancellationToken cancellationToken, - TaskContinuationOptions continuationOptions, - TaskScheduler scheduler) - { - Func continuationFunction = antecedent => - { - continuationAction(antecedent); - return true; - }; - - return task.SafeContinueWith(continuationFunction, cancellationToken, continuationOptions, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Func, TResult> continuationFunction, - CancellationToken cancellationToken, - TaskScheduler scheduler) - { - return SafeContinueWith( - task, continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Func, TResult> continuationFunction, - CancellationToken cancellationToken, - TaskContinuationOptions continuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWith( - (Task antecedent) => continuationFunction((Task)antecedent), cancellationToken, continuationOptions, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Action> continuationAction, - CancellationToken cancellationToken, - TaskContinuationOptions continuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWith( - (Task antecedent) => continuationAction((Task)antecedent), cancellationToken, continuationOptions, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Func continuationFunction, - CancellationToken cancellationToken, - TaskContinuationOptions continuationOptions, - TaskScheduler scheduler) - { - // So here's the deal. Say you do the following: -#if false - // CancellationToken ct1 = ..., ct2 = ...; - - // Task A = Task.Factory.StartNew(..., ct1); - // Task B = A.ContinueWith(..., ct1); - // Task C = B.ContinueWith(..., ct2); -#endif - // If ct1 is cancelled then the following may occur: - // 1) Task A can still be running (as it hasn't responded to the cancellation request - // yet). - // 2) Task C can start running. How? Well if B hasn't started running, it may - // immediately transition to the 'Cancelled/Completed' state. Moving to that state will - // immediately trigger C to run. - // - // We do not want this, so we pass the LazyCancellation flag to the TPL which implements - // the behavior we want. - - Func outerFunction = t => - { - try - { - return continuationFunction(t); - } - catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) - { - throw ExceptionUtilities.Unreachable; - } - }; - - // This is the only place in the code where we're allowed to call ContinueWith. - return task.ContinueWith(outerFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Func continuationFunction, - CancellationToken cancellationToken, - TaskScheduler scheduler) - { - return task.SafeContinueWith(continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Action continuationAction, - TaskScheduler scheduler) - { - return task.SafeContinueWith(continuationAction, CancellationToken.None, TaskContinuationOptions.None, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Action> continuationFunction, - TaskScheduler scheduler) - { - return task.SafeContinueWith(continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Func, TResult> continuationFunction, - TaskScheduler scheduler) - { - return task.SafeContinueWith(continuationFunction, CancellationToken.None, TaskContinuationOptions.None, scheduler); - } - - public static Task SafeContinueWith( - this Task task, - Action continuationAction, - CancellationToken cancellationToken, - TaskScheduler scheduler) - { - return task.SafeContinueWith(continuationAction, cancellationToken, TaskContinuationOptions.None, scheduler); - } - - // Code provided by Stephen Toub. - public static Task ContinueWithAfterDelay( - this Task task, - Func, TResult> continuationFunction, - CancellationToken cancellationToken, - int millisecondsDelay, - TaskContinuationOptions taskContinuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWith(t => - Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWith( - _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler), - cancellationToken, taskContinuationOptions, scheduler).Unwrap(); - } - - public static Task ContinueWithAfterDelay( - this Task task, - Func continuationFunction, - CancellationToken cancellationToken, - int millisecondsDelay, - TaskContinuationOptions taskContinuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWith(t => - Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWith( - _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler), - cancellationToken, taskContinuationOptions, scheduler).Unwrap(); - } - - public static Task ContinueWithAfterDelay( - this Task task, - Action continuationAction, - CancellationToken cancellationToken, - int millisecondsDelay, - TaskContinuationOptions taskContinuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWith(t => - Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWith( - _ => continuationAction(), cancellationToken, TaskContinuationOptions.None, scheduler), - cancellationToken, taskContinuationOptions, scheduler).Unwrap(); - } - - public static Task SafeContinueWithFromAsync( - this Task task, - Func, Task> continuationFunction, - CancellationToken cancellationToken, - TaskContinuationOptions continuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWithFromAsync( - (Task antecedent) => continuationFunction((Task)antecedent), cancellationToken, continuationOptions, scheduler); - } - - public static Task SafeContinueWithFromAsync( - this Task task, - Func> continuationFunction, - CancellationToken cancellationToken, - TaskContinuationOptions continuationOptions, - TaskScheduler scheduler) - { - // So here's the deal. Say you do the following: -#if false - // CancellationToken ct1 = ..., ct2 = ...; - - // Task A = Task.Factory.StartNew(..., ct1); - // Task B = A.ContinueWith(..., ct1); - // Task C = B.ContinueWith(..., ct2); -#endif - // If ct1 is cancelled then the following may occur: - // 1) Task A can still be running (as it hasn't responded to the cancellation request - // yet). - // 2) Task C can start running. How? Well if B hasn't started running, it may - // immediately transition to the 'Cancelled/Completed' state. Moving to that state will - // immediately trigger C to run. - // - // We do not want this, so we pass the LazyCancellation flag to the TPL which implements - // the behavior we want. - // This is the only place in the code where we're allowed to call ContinueWith. - var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap(); - - nextTask.ContinueWith(ReportFatalError, continuationFunction, - CancellationToken.None, - TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - - return nextTask; - } - - public static Task SafeContinueWithFromAsync( - this Task task, - Func continuationFunction, - CancellationToken cancellationToken, - TaskScheduler scheduler) - { - return task.SafeContinueWithFromAsync(continuationFunction, cancellationToken, TaskContinuationOptions.None, scheduler); - } - - public static Task SafeContinueWithFromAsync( - this Task task, - Func continuationFunction, - CancellationToken cancellationToken, - TaskContinuationOptions continuationOptions, - TaskScheduler scheduler) - { - // So here's the deal. Say you do the following: -#if false - // CancellationToken ct1 = ..., ct2 = ...; - - // Task A = Task.Factory.StartNew(..., ct1); - // Task B = A.ContinueWith(..., ct1); - // Task C = B.ContinueWith(..., ct2); -#endif - // If ct1 is cancelled then the following may occur: - // 1) Task A can still be running (as it hasn't responded to the cancellation request - // yet). - // 2) Task C can start running. How? Well if B hasn't started running, it may - // immediately transition to the 'Cancelled/Completed' state. Moving to that state will - // immediately trigger C to run. - // - // We do not want this, so we pass the LazyCancellation flag to the TPL which implements - // the behavior we want. - // This is the only place in the code where we're allowed to call ContinueWith. - var nextTask = task.ContinueWith(continuationFunction, cancellationToken, continuationOptions | TaskContinuationOptions.LazyCancellation, scheduler).Unwrap(); - ReportFatalError(nextTask, continuationFunction); - return nextTask; - } - - public static Task ContinueWithAfterDelayFromAsync( - this Task task, - Func> continuationFunction, - CancellationToken cancellationToken, - int millisecondsDelay, - TaskContinuationOptions taskContinuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWith(t => - Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWithFromAsync( - _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler), - cancellationToken, taskContinuationOptions, scheduler).Unwrap(); - } - - public static Task ContinueWithAfterDelayFromAsync( - this Task task, - Func continuationFunction, - CancellationToken cancellationToken, - int millisecondsDelay, - TaskContinuationOptions taskContinuationOptions, - TaskScheduler scheduler) - { - return task.SafeContinueWith(t => - Task.Delay(millisecondsDelay, cancellationToken).SafeContinueWithFromAsync( - _ => continuationFunction(t), cancellationToken, TaskContinuationOptions.None, scheduler), - cancellationToken, taskContinuationOptions, scheduler).Unwrap(); - } - - internal static void ReportFatalError(Task task, object continuationFunction) - { - task.ContinueWith(ReportFatalErrorWorker, continuationFunction, - CancellationToken.None, - TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - } - - [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] - private static void ReportFatalErrorWorker(Task task, object continuationFunction) - { - var exception = task.Exception; - var methodInfo = ((Delegate)continuationFunction).GetMethodInfo(); - exception.Data["ContinuationFunction"] = methodInfo.DeclaringType.FullName + "::" + methodInfo.Name; - - // In case of a crash with ExecutionEngineException w/o call stack it might be possible to get the stack trace using WinDbg: - // > !threads // find thread with System.ExecutionEngineException - // ... - // 67 65 4760 692b5d60 1029220 Preemptive CD9AE70C:FFFFFFFF 012ad0f8 0 MTA (Threadpool Worker) System.ExecutionEngineException 03c51108 - // ... - // > ~67s // switch to thread 67 - // > !dso // dump stack objects - FatalError.Report(exception); - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/TaskFactoryExtensions.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/TaskFactoryExtensions.cs deleted file mode 100644 index 5dcfc0d730f04..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/TaskFactoryExtensions.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.VisualStudio.InteractiveWindow; - -namespace Roslyn.Utilities -{ - [SuppressMessage("ApiDesign", "CA1068", Justification = "Matching TPL Signatures")] - internal static partial class TaskFactoryExtensions - { - public static Task SafeStartNew(this TaskFactory factory, Action action, CancellationToken cancellationToken, TaskScheduler scheduler) - { - return factory.SafeStartNew(action, cancellationToken, TaskCreationOptions.None, scheduler); - } - - public static Task SafeStartNew( - this TaskFactory factory, - Action action, - CancellationToken cancellationToken, - TaskCreationOptions creationOptions, - TaskScheduler scheduler) - { - Action wrapped = () => - { - try - { - action(); - } - catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) - { - throw ExceptionUtilities.Unreachable; - } - }; - - // The one and only place we can call StartNew(). - return factory.StartNew(wrapped, cancellationToken, creationOptions, scheduler); - } - - public static Task SafeStartNew(this TaskFactory factory, Func func, CancellationToken cancellationToken, TaskScheduler scheduler) - { - return factory.SafeStartNew(func, cancellationToken, TaskCreationOptions.None, scheduler); - } - - public static Task SafeStartNew( - this TaskFactory factory, - Func func, - CancellationToken cancellationToken, - TaskCreationOptions creationOptions, - TaskScheduler scheduler) - { - Func wrapped = () => - { - try - { - return func(); - } - catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) - { - throw ExceptionUtilities.Unreachable; - } - }; - - // The one and only place we can call StartNew<>(). - return factory.StartNew(wrapped, cancellationToken, creationOptions, scheduler); - } - - public static Task SafeStartNewFromAsync(this TaskFactory factory, Func actionAsync, CancellationToken cancellationToken, TaskScheduler scheduler) - { - return factory.SafeStartNewFromAsync(actionAsync, cancellationToken, TaskCreationOptions.None, scheduler); - } - - public static Task SafeStartNewFromAsync( - this TaskFactory factory, - Func actionAsync, - CancellationToken cancellationToken, - TaskCreationOptions creationOptions, - TaskScheduler scheduler) - { - // The one and only place we can call StartNew<>(). - var task = factory.StartNew(actionAsync, cancellationToken, creationOptions, scheduler).Unwrap(); - TaskExtensions.ReportFatalError(task, actionAsync); - return task; - } - - public static Task SafeStartNewFromAsync(this TaskFactory factory, Func> funcAsync, CancellationToken cancellationToken, TaskScheduler scheduler) - { - return factory.SafeStartNewFromAsync(funcAsync, cancellationToken, TaskCreationOptions.None, scheduler); - } - - public static Task SafeStartNewFromAsync( - this TaskFactory factory, - Func> funcAsync, - CancellationToken cancellationToken, - TaskCreationOptions creationOptions, - TaskScheduler scheduler) - { - // The one and only place we can call StartNew<>(). - var task = factory.StartNew(funcAsync, cancellationToken, creationOptions, scheduler).Unwrap(); - TaskExtensions.ReportFatalError(task, funcAsync); - return task; - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfFactAttribute.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfFactAttribute.cs deleted file mode 100644 index 39d1faf1ef2c1..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfFactAttribute.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -using Xunit; -using Xunit.Sdk; - -namespace Roslyn.Test.Utilities -{ - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - [XunitTestCaseDiscoverer("Roslyn.Test.Utilities.WpfFactDiscoverer", "Microsoft.VisualStudio.InteractiveWindow.UnitTests")] - public class WpfFactAttribute : FactAttribute { } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfFactDiscoverer.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfFactDiscoverer.cs deleted file mode 100644 index 7660a6ea69326..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfFactDiscoverer.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Threading; -using Xunit.Abstractions; -using Xunit.Sdk; - -namespace Roslyn.Test.Utilities -{ - public class WpfFactDiscoverer : FactDiscoverer - { - private readonly IMessageSink _diagnosticMessageSink; - - /// - /// A used to ensure that only a single -attributed test runs at once. - /// This requirement must be made because, currently, 's logic sets various static state before a method - /// runs. If two tests run interleaved on the same scheduler (i.e. if one yields with an await) then all bets are off. - /// - private readonly SemaphoreSlim _wpfTestSerializationGate = new SemaphoreSlim(initialCount: 1); - - public WpfFactDiscoverer(IMessageSink diagnosticMessageSink) : base(diagnosticMessageSink) - { - _diagnosticMessageSink = diagnosticMessageSink; - } - - protected override IXunitTestCase CreateTestCase(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo factAttribute) - => new WpfTestCase(_diagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod, _wpfTestSerializationGate); - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfTestCase.cs b/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfTestCase.cs deleted file mode 100644 index 60a4010d5e99d..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/Threading/WpfTestCase.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Threading; - -using Xunit.Abstractions; -using Xunit.Sdk; -using Roslyn.Utilities; -using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Utilities; - -namespace Roslyn.Test.Utilities -{ - public class WpfTestCase : XunitTestCase - { - private readonly SemaphoreSlim _wpfTestSerializationGate; - - public WpfTestCase(IMessageSink diagnosticMessageSink, TestMethodDisplay defaultMethodDisplay, ITestMethod testMethod, SemaphoreSlim wpfTestSerializationGate, object[] testMethodArguments = null) - : base(diagnosticMessageSink, defaultMethodDisplay, testMethod, testMethodArguments) - { - _wpfTestSerializationGate = wpfTestSerializationGate; - } - - public override Task RunAsync(IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) - { - var sta = StaTaskScheduler.DefaultSta; - var task = Task.Factory.StartNew(async () => - { - Debug.Assert(sta.Threads.Length == 1); - Debug.Assert(sta.Threads[0] == Thread.CurrentThread); - - using (await _wpfTestSerializationGate.DisposableWaitAsync()) - { - try - { - // Sync up FTAO to the context that we are creating here. - ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = new ForegroundThreadData( - Thread.CurrentThread, - StaTaskScheduler.DefaultSta, - ForegroundThreadDataKind.StaUnitTest); - - // Reset our flag ensuring that part of this test actually needs WpfFact - s_wpfFactRequirementReason = null; - - // All WPF Tests need a DispatcherSynchronizationContext and we dont want to block pending keyboard - // or mouse input from the user. So use background priority which is a single level below user input. - var dispatcherSynchronizationContext = new DispatcherSynchronizationContext(); - - // xUnit creates its own synchronization context and wraps any existing context so that messages are - // still pumped as necessary. So we are safe setting it here, where we are not safe setting it in test. - SynchronizationContext.SetSynchronizationContext(dispatcherSynchronizationContext); - - // Just call back into the normal xUnit dispatch process now that we are on an STA Thread with no synchronization context. - var baseTask = base.RunAsync(diagnosticMessageSink, messageBus, constructorArguments, aggregator, cancellationTokenSource); - do - { - var delay = Task.Delay(TimeSpan.FromMilliseconds(10), cancellationTokenSource.Token); - var completed = await Task.WhenAny(baseTask, delay).ConfigureAwait(false); - if (completed == baseTask) - { - return await baseTask.ConfigureAwait(false); - } - - // Schedule a task to pump messages on the UI thread. - await Task.Factory.StartNew( - () => WaitHelper.WaitForDispatchedOperationsToComplete(DispatcherPriority.ApplicationIdle), - cancellationTokenSource.Token, - TaskCreationOptions.None, - sta).ConfigureAwait(false); - } - while (true); - } - finally - { - ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = null; - s_wpfFactRequirementReason = null; - - // Cleanup the synchronization context even if the test is failing exceptionally - SynchronizationContext.SetSynchronizationContext(null); - } - } - }, cancellationTokenSource.Token, TaskCreationOptions.None, sta); - - return task.Unwrap(); - } - - private static string s_wpfFactRequirementReason; - - /// - /// Asserts that the test is running on a test method, and records the reason for requiring the . - /// - public static void RequireWpfFact(string reason) - { - if (ForegroundThreadDataInfo.CurrentForegroundThreadDataKind != ForegroundThreadDataKind.StaUnitTest) - { - throw new Exception($"This test requires {nameof(WpfFactAttribute)} because '{reason}' but is missing {nameof(WpfFactAttribute)}. Either the attribute should be changed, or the reason it needs an STA thread audited."); - } - - s_wpfFactRequirementReason = reason; - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestUtilities/ThrowingTraceListener.cs b/src/InteractiveWindow/EditorTest/TestUtilities/ThrowingTraceListener.cs deleted file mode 100644 index ec259c8001ab8..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestUtilities/ThrowingTraceListener.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; - -namespace Microsoft.CodeAnalysis -{ - // To enable this for a process, add the following to the app.config for the project: - // - // - // - // - // - // - // - // - // - // - // - public sealed class ThrowingTraceListener : TraceListener - { - public override void Fail(string message, string detailMessage) - { - throw new DebugAssertFailureException(message + Environment.NewLine + detailMessage); - } - - public override void Write(object o) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, null, o?.ToString()); - } - } - - public override void Write(object o, string category) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, category, o?.ToString()); - } - } - - public override void Write(string message) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, null, message); - } - } - - public override void Write(string message, string category) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, category, message); - } - } - - public override void WriteLine(object o) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, null, o?.ToString() + Environment.NewLine); - } - } - - public override void WriteLine(object o, string category) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, category, o?.ToString() + Environment.NewLine); - } - } - - public override void WriteLine(string message) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, null, message + Environment.NewLine); - } - } - - public override void WriteLine(string message, string category) - { - if (Debugger.IsLogging()) - { - Debugger.Log(0, category, message + Environment.NewLine); - } - } - - [Serializable] - public class DebugAssertFailureException : Exception - { - public DebugAssertFailureException() { } - public DebugAssertFailureException(string message) : base(message) { } - public DebugAssertFailureException(string message, Exception inner) : base(message, inner) { } - protected DebugAssertFailureException( - System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) : base(info, context) - { } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/TestWaitIndicator.cs b/src/InteractiveWindow/EditorTest/TestWaitIndicator.cs deleted file mode 100644 index 0c21ccd2a6a8e..0000000000000 --- a/src/InteractiveWindow/EditorTest/TestWaitIndicator.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.ComponentModel.Composition; -using System.Threading; -using Microsoft.VisualStudio.Language.Intellisense.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests -{ - [Export(typeof(IWaitIndicator))] - internal class TestWaitIndicator : IWaitIndicator - { - public IWaitContext StartWait(string title, string message, bool allowCancel) - { - return new WaitContext(); - } - - public WaitIndicatorResult Wait(string title, string message, bool allowCancel, Action action) - { - try - { - action(new WaitContext()); - } - catch - { - } - - return WaitIndicatorResult.Completed; - } - - private class WaitContext : IWaitContext - { - public bool AllowCancel - { - get - { - return false; - } - - set - { - } - } - - public CancellationToken CancellationToken - { - get - { - return CancellationToken.None; - } - } - - public string Message - { - get - { - return string.Empty; - } - - set - { - } - } - - public void UpdateProgress() - { - } - - public void Dispose() - { - } - } - } -} diff --git a/src/InteractiveWindow/EditorTest/app.config b/src/InteractiveWindow/EditorTest/app.config deleted file mode 100644 index 3e34ac2820214..0000000000000 --- a/src/InteractiveWindow/EditorTest/app.config +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/InteractiveWindow/EditorTest/project.json b/src/InteractiveWindow/EditorTest/project.json deleted file mode 100644 index f1d501515b5ce..0000000000000 --- a/src/InteractiveWindow/EditorTest/project.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "dependencies": { - "System.Collections.Immutable": "1.2.0", - "BasicUndo": "0.9.3", - "RoslynDependencies.Microsoft.VisualStudio.Platform.VSEditor": "14.3.25407", - "Moq": "4.2.1402.2112", - "xunit": "2.1.0", - "xunit.runner.console": "2.2.0-beta1-build3239", - "Microsoft.VisualStudio.Text.UI": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Text.UI.Wpf": { - "version": "14.3.25407", - "suppressParent": "all" - }, - }, - "frameworks": { - "net46": { } - }, - "runtimes": { - "win7": { } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/InteractiveWindow.sln b/src/InteractiveWindow/InteractiveWindow.sln deleted file mode 100644 index 27cc46a343886..0000000000000 --- a/src/InteractiveWindow/InteractiveWindow.sln +++ /dev/null @@ -1,71 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.21803.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveWindow", "Editor\InteractiveWindow.csproj", "{01E9BD68-0339-4A13-B42F-A3CA84D164F3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveWindowTest", "EditorTest\InteractiveWindowTest.csproj", "{7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VisualStudioInteractiveWindow", "VisualStudio\VisualStudioInteractiveWindow.csproj", "{20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Debug|x86.ActiveCfg = Debug|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Any CPU.Build.0 = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {01E9BD68-0339-4A13-B42F-A3CA84D164F3}.Release|x86.ActiveCfg = Release|Any CPU - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|Any CPU.ActiveCfg = Debug|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|x86.ActiveCfg = Debug|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Debug|x86.Build.0 = Debug|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|Any CPU.ActiveCfg = Release|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|Mixed Platforms.Build.0 = Release|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|x86.ActiveCfg = Release|x86 - {7F3CB45E-4993-4FA4-8D6A-C2DFFED2DFC3}.Release|x86.Build.0 = Release|x86 - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Debug|x86.ActiveCfg = Debug|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Any CPU.Build.0 = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F}.Release|x86.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(TeamFoundationVersionControl) = preSolution - SccNumberOfProjects = 4 - SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C} - SccTeamFoundationServer = http://vstfdevdiv:8080/devdiv2 - SccLocalPath0 = . - SccProjectUniqueName1 = Editor\\InteractiveWindow.csproj - SccProjectName1 = Editor - SccLocalPath1 = Editor - SccProjectUniqueName2 = EditorTest\\InteractiveWindowTest.csproj - SccProjectName2 = EditorTest - SccLocalPath2 = EditorTest - SccProjectUniqueName3 = VisualStudio\\VisualStudioInteractiveWindow.csproj - SccProjectName3 = VisualStudio - SccLocalPath3 = VisualStudio - EndGlobalSection -EndGlobal diff --git a/src/InteractiveWindow/VisualStudio/AssemblyRedirects.cs b/src/InteractiveWindow/VisualStudio/AssemblyRedirects.cs deleted file mode 100644 index 9995fb99c1fc8..0000000000000 --- a/src/InteractiveWindow/VisualStudio/AssemblyRedirects.cs +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.InteractiveWindow.Shell; - -[assembly: ProvideInteractiveWindowBindingRedirection("Microsoft.VisualStudio.InteractiveWindow.dll")] -[assembly: ProvideInteractiveWindowBindingRedirection("Microsoft.VisualStudio.VsInteractiveWindow.dll")] \ No newline at end of file diff --git a/src/InteractiveWindow/VisualStudio/CommandIds.cs b/src/InteractiveWindow/VisualStudio/CommandIds.cs deleted file mode 100644 index 21d7c4f9fc7dd..0000000000000 --- a/src/InteractiveWindow/VisualStudio/CommandIds.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - internal enum CommandIds : uint - { - // TODO (crwilcox): should all of these be in the editoroperations? - SmartExecute = 0x103, - AbortExecution = 0x104, - Reset = 0x105, - HistoryNext = 0x0106, - HistoryPrevious = 0x0107, - ClearScreen = 0x0108, - BreakLine = 0x0109, - SearchHistoryNext = 0x010A, - SearchHistoryPrevious = 0x010B, - ExecuteInInteractiveWindow = 0x010C, - CopyToInteractiveWindow = 0x010D, - CopyCode = 0x010E, - } -} diff --git a/src/InteractiveWindow/VisualStudio/ContentTypeMetadata.cs b/src/InteractiveWindow/VisualStudio/ContentTypeMetadata.cs deleted file mode 100644 index fda9ac25232e3..0000000000000 --- a/src/InteractiveWindow/VisualStudio/ContentTypeMetadata.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - internal class ContentTypeMetadata - { - public IEnumerable ContentTypes { get; } - - public ContentTypeMetadata(IDictionary data) - { - this.ContentTypes = (IEnumerable)data["ContentTypes"]; - } - } - - internal static class ContentTypeMetadataHelpers - { - public static T OfContentType( - this IEnumerable> exports, - IContentType contentType, - IContentTypeRegistryService contentTypeRegistry) - { - return (from export in exports - from exportedContentTypeName in export.Metadata.ContentTypes - let exportedContentType = contentTypeRegistry.GetContentType(exportedContentTypeName) - where exportedContentType.IsOfType(contentType.TypeName) - select export.Value).SingleOrDefault(); - } - } -} diff --git a/src/InteractiveWindow/VisualStudio/Guids.cs b/src/InteractiveWindow/VisualStudio/Guids.cs deleted file mode 100644 index 103a83402e58e..0000000000000 --- a/src/InteractiveWindow/VisualStudio/Guids.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - public static class Guids - { - // vsct guids: - // This GUID identifies the VsInteractiveWindow type. We need to pass it to VS in a string form. - public const string InteractiveToolWindowIdString = "2D0A56AA-9527-4B78-B6E6-EBE6E05DA749"; - public const string InteractiveWindowPackageIdString = "F5199A4E-6A60-4F79-82E9-FC92A41C4610"; - public const string InteractiveCommandSetIdString = "00B8868B-F9F5-4970-A048-410B05508506"; - - public static readonly Guid InteractiveToolWindowId = new Guid(InteractiveToolWindowIdString); - public static readonly Guid InteractiveWindowPackageId = new Guid(InteractiveWindowPackageIdString); - public static readonly Guid InteractiveCommandSetId = new Guid(InteractiveCommandSetIdString); - } -} diff --git a/src/InteractiveWindow/VisualStudio/IVsInteractiveWindow.cs b/src/InteractiveWindow/VisualStudio/IVsInteractiveWindow.cs deleted file mode 100644 index 1289a2533cac4..0000000000000 --- a/src/InteractiveWindow/VisualStudio/IVsInteractiveWindow.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.VisualStudio.InteractiveWindow; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - /// - /// Provides access to an interactive window being hosted inside of Visual Studio's process using the - /// default tool window. - /// - /// These tool windows are created using ProvideInteractiveWindowAttribute which provides the normal - /// tool window registration options. Instances of the tool window are then created using - /// IVsInteractiveWindowFactory when VS calls on your packages IVsToolWindowFactory.CreateToolWindow - /// method. - /// - public interface IVsInteractiveWindow - { - /// - /// Gets the interactive window instance. - /// - IInteractiveWindow InteractiveWindow { get; } - - /// - /// Shows the window. - /// - void Show(bool focus); - - /// - /// Configures the window for the specified VS language service guid language preferences. - /// - /// Also installs a language appropriate command filter if one is exported via IVsInteractiveWindowOleCommandTargetProvider. - /// - void SetLanguage(Guid languageServiceGuid, IContentType contentType); - } -} diff --git a/src/InteractiveWindow/VisualStudio/IVsInteractiveWindowFactory.cs b/src/InteractiveWindow/VisualStudio/IVsInteractiveWindowFactory.cs deleted file mode 100644 index 7b1a4d7f26a3d..0000000000000 --- a/src/InteractiveWindow/VisualStudio/IVsInteractiveWindowFactory.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.VisualStudio.InteractiveWindow; -using Microsoft.VisualStudio.Shell.Interop; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - public interface IVsInteractiveWindowFactory - { - IVsInteractiveWindow Create(Guid providerId, int instanceId, string title, IInteractiveEvaluator evaluator, __VSCREATETOOLWIN creationFlags = 0); - } -} diff --git a/src/InteractiveWindow/VisualStudio/IVsInteractiveWindowOleCommandTargetProvider.cs b/src/InteractiveWindow/VisualStudio/IVsInteractiveWindowOleCommandTargetProvider.cs deleted file mode 100644 index 62468c86960f0..0000000000000 --- a/src/InteractiveWindow/VisualStudio/IVsInteractiveWindowOleCommandTargetProvider.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.OLE.Interop; -using Microsoft.VisualStudio.Text.Editor; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - /// - /// The implementer is given a chance to attach a command filter that routes language services - /// commands into the Interactive Window command filter chain. - /// - public interface IVsInteractiveWindowOleCommandTargetProvider - { - IOleCommandTarget GetCommandTarget(IWpfTextView textView, IOleCommandTarget nextTarget); - } -} diff --git a/src/InteractiveWindow/VisualStudio/InteractiveWindow.vsct b/src/InteractiveWindow/VisualStudio/InteractiveWindow.vsct deleted file mode 100644 index af1d52e368444..0000000000000 --- a/src/InteractiveWindow/VisualStudio/InteractiveWindow.vsct +++ /dev/null @@ -1,350 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Interactive Console - Interactive Console - - - - - - DefaultDocked - NoToolbarClose - AlwaysCreate - TextChanges - - Interactive Window - Interactive Window - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/InteractiveWindow/VisualStudio/InteractiveWindowPackage.cs b/src/InteractiveWindow/VisualStudio/InteractiveWindowPackage.cs deleted file mode 100644 index 895b71489c7df..0000000000000 --- a/src/InteractiveWindow/VisualStudio/InteractiveWindowPackage.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.ComponentModel; -using System.Runtime.InteropServices; -using Microsoft.VisualStudio.Shell; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - /// - /// This is the class that implements the package exposed by this assembly. - /// - /// The minimum requirement for a class to be considered a valid package for Visual Studio - /// is to implement the IVsPackage interface and register itself with the shell. - /// This package uses the helper classes defined inside the Managed Package Framework (MPF) - /// to do it: it derives from the Package class that provides the implementation of the - /// IVsPackage interface and uses the registration attributes defined in the framework to - /// register itself and its components with the shell. - /// - // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is - // a package. - [PackageRegistration(UseManagedResourcesOnly = true)] - [Description("Visual Studio Interactive Window")] - [ProvideKeyBindingTable(Guids.InteractiveToolWindowIdString, 200)] // Resource ID: "Interactive Window" - [ProvideMenuResource("Menus.ctmenu", 4)] - [Guid(Guids.InteractiveWindowPackageIdString)] - [ProvideBindingPath] // make sure our DLLs are loadable from other packages - internal sealed class InteractiveWindowPackage : Package - { - } -} diff --git a/src/InteractiveWindow/VisualStudio/MenuIds.cs b/src/InteractiveWindow/VisualStudio/MenuIds.cs deleted file mode 100644 index 795217bc59e21..0000000000000 --- a/src/InteractiveWindow/VisualStudio/MenuIds.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Microsoft.VisualStudio -{ - internal enum MenuIds : uint - { - InteractiveWindowToolbar = 0x2000, - InteractiveWindowContextMenu = 0x2100, - } -} diff --git a/src/InteractiveWindow/VisualStudio/Properties/AssemblyInfo.cs b/src/InteractiveWindow/VisualStudio/Properties/AssemblyInfo.cs deleted file mode 100644 index 5ea21f55a92cb..0000000000000 --- a/src/InteractiveWindow/VisualStudio/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -[assembly: AssemblyTitle("Visual Studio Interactive Window")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] - -[assembly: InternalsVisibleTo("AnalysisTest, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] diff --git a/src/InteractiveWindow/VisualStudio/ProvideBindingRedirection.cs b/src/InteractiveWindow/VisualStudio/ProvideBindingRedirection.cs deleted file mode 100644 index 6c2cff2511b61..0000000000000 --- a/src/InteractiveWindow/VisualStudio/ProvideBindingRedirection.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.VisualStudio.Shell; -using System.IO; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - /// - /// A that provides binding redirects with all of the settings we need. - /// It's just a wrapper for that sets all the defaults rather than duplicating them. - /// - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - internal sealed class ProvideInteractiveWindowBindingRedirectionAttribute : RegistrationAttribute - { - private readonly ProvideBindingRedirectionAttribute _redirectionAttribute; - - public ProvideInteractiveWindowBindingRedirectionAttribute(string fileName) - { - // ProvideBindingRedirectionAttribute is sealed, so we can't inherit from it to provide defaults. - // Instead, we'll do more of an aggregation pattern here. - // Note that PublicKeyToken, NewVersion and OldVersionUpperBound are read from the actual assembly version of the dll. - _redirectionAttribute = new ProvideBindingRedirectionAttribute - { - AssemblyName = Path.GetFileNameWithoutExtension(fileName), - OldVersionLowerBound = "0.0.0.0", - CodeBase = fileName, - }; - } - - public override void Register(RegistrationContext context) - { - _redirectionAttribute.Register(context); - - // Opt into overriding the devenv.exe.config binding redirect - using (var key = context.CreateKey(@"RuntimeConfiguration\dependentAssembly\bindingRedirection\" + _redirectionAttribute.Guid.ToString("B").ToUpperInvariant())) - { - key.SetValue("isPkgDefOverrideEnabled", true); - } - } - - public override void Unregister(RegistrationContext context) - { - _redirectionAttribute.Unregister(context); - } - } -} diff --git a/src/InteractiveWindow/VisualStudio/ProvideInteractiveWindowAttribute.cs b/src/InteractiveWindow/VisualStudio/ProvideInteractiveWindowAttribute.cs deleted file mode 100644 index eacef65b6cf1a..0000000000000 --- a/src/InteractiveWindow/VisualStudio/ProvideInteractiveWindowAttribute.cs +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Drawing; -using System.Globalization; -using Microsoft.VisualStudio.Shell; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - /// - /// This attribute declares that a package own an interactive window. Visual Studio uses this - /// information to handle the positioning and persistence of your window. The attributes on a - /// package do not control the behavior of the package, but they can be used by registration - /// tools to register the proper information with Visual Studio. - /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] - public sealed class ProvideInteractiveWindowAttribute : RegistrationAttribute - { - public ProvideInteractiveWindowAttribute(string guid) - { - this.Id = new Guid(guid); - } - - public Guid Id { get; } - - public Rectangle Position { get; set; } - - /// - /// Default DockStyle for the ToolWindow - /// - public VsDockStyle Style { get; set; } - - /// - /// Default width of the ToolWindow when docked - /// - public int DockedWidth { get; set; } - - /// - /// Default height of the ToolWindow when docked - /// - public int DockedHeight { get; set; } - - /// - /// Default Orientation for the ToolWindow, relative to the window specified by the Window Property - /// - public ToolWindowOrientation Orientation { get; set; } - - /// - /// Default Window that the ToolWindow will be docked with - /// - public string Window { get; set; } - - /// - /// Set to true if you want a tool window that behaves and has a lifetime like a document. - /// The tool window will only be MDI or floating and will remain visible in its position across all layout changes - /// until manually closed by the user at which point it will be destroyed. - /// This flag implies DontForceCreate and destructive multi instance. - /// - public bool DocumentLikeTool { get; set; } - - private string GetRegistryKeyName() - { - return "ToolWindows\\" + Id.ToString("B"); - } - - /// - /// Called to register this attribute with the given context. The context - /// contains the location where the registration information should be placed. - /// it also contains such as the type being registered, and path information. - /// - public override void Register(RegistrationContext context) - { - using (Key childKey = context.CreateKey(GetRegistryKeyName())) - { - // Package owning this tool window - childKey.SetValue(string.Empty, context.ComponentType.GUID.ToString("B")); - - if (Orientation != ToolWindowOrientation.none) - { - childKey.SetValue("Orientation", OrientationToString(Orientation)); - } - - if (Style != VsDockStyle.none) - { - childKey.SetValue("Style", StyleToString(Style)); - } - - if (!string.IsNullOrEmpty(Window)) - { - childKey.SetValue("Window", Window); - } - - if (Position.Width != 0 && Position.Height != 0) - { - string positionString = string.Format(CultureInfo.InvariantCulture, "{0}, {1}, {2}, {3}", - Position.Left, - Position.Top, - Position.Right, - Position.Bottom); - - childKey.SetValue("Float", positionString); - } - - if (DockedWidth > 0) - { - childKey.SetValue("DockedWidth", DockedWidth); - } - - if (DockedHeight > 0) - { - childKey.SetValue("DockedHeight", DockedHeight); - } - - if (DocumentLikeTool) - { - childKey.SetValue("DocumentLikeTool", 1); - } - } - } - - /// - /// Unregister this Tool Window. - /// - public override void Unregister(RegistrationContext context) - { - context.RemoveKey(GetRegistryKeyName()); - } - - private string StyleToString(VsDockStyle style) - { - switch (style) - { - case VsDockStyle.MDI: return "MDI"; - case VsDockStyle.Float: return "Float"; - case VsDockStyle.Linked: return "Linked"; - case VsDockStyle.Tabbed: return "Tabbed"; - case VsDockStyle.AlwaysFloat: return "AlwaysFloat"; - case VsDockStyle.none: return string.Empty; - default: - // TODO: error message - throw new ArgumentException("Style"); - } - } - - private string OrientationToString(ToolWindowOrientation position) - { - switch (position) - { - case ToolWindowOrientation.Top: return "Top"; - case ToolWindowOrientation.Left: return "Left"; - case ToolWindowOrientation.Right: return "Right"; - case ToolWindowOrientation.Bottom: return "Bottom"; - case ToolWindowOrientation.none: return string.Empty; - default: - // TODO: error message - throw new ArgumentException("Orientation"); - } - } - } -} - diff --git a/src/InteractiveWindow/VisualStudio/PublicAPI.Shipped.txt b/src/InteractiveWindow/VisualStudio/PublicAPI.Shipped.txt deleted file mode 100644 index dc0e048ec1507..0000000000000 --- a/src/InteractiveWindow/VisualStudio/PublicAPI.Shipped.txt +++ /dev/null @@ -1,39 +0,0 @@ -Microsoft.VisualStudio.InteractiveWindow.Shell.Guids -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindow -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindow.InteractiveWindow.get -> Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindow.SetLanguage(System.Guid languageServiceGuid, Microsoft.VisualStudio.Utilities.IContentType contentType) -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindow.Show(bool focus) -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory.Create(System.Guid providerId, int instanceId, string title, Microsoft.VisualStudio.InteractiveWindow.IInteractiveEvaluator evaluator, Microsoft.VisualStudio.Shell.Interop.__VSCREATETOOLWIN creationFlags = (Microsoft.VisualStudio.Shell.Interop.__VSCREATETOOLWIN)0) -> Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindow -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowOleCommandTargetProvider -Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowOleCommandTargetProvider.GetCommandTarget(Microsoft.VisualStudio.Text.Editor.IWpfTextView textView, Microsoft.VisualStudio.OLE.Interop.IOleCommandTarget nextTarget) -> Microsoft.VisualStudio.OLE.Interop.IOleCommandTarget -Microsoft.VisualStudio.InteractiveWindow.Shell.InteractiveWindowPackage -Microsoft.VisualStudio.InteractiveWindow.Shell.InteractiveWindowPackage.InteractiveWindowPackage() -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.DockedHeight.get -> int -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.DockedHeight.set -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.DockedWidth.get -> int -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.DockedWidth.set -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.DocumentLikeTool.get -> bool -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.DocumentLikeTool.set -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Id.get -> System.Guid -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Orientation.get -> Microsoft.VisualStudio.Shell.ToolWindowOrientation -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Orientation.set -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Position.get -> System.Drawing.Rectangle -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Position.set -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.ProvideInteractiveWindowAttribute(string guid) -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Style.get -> Microsoft.VisualStudio.Shell.VsDockStyle -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Style.set -> void -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Window.get -> string -Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Window.set -> void -Microsoft.VisualStudio.VsInteractiveWindowExtensions -const Microsoft.VisualStudio.InteractiveWindow.Shell.Guids.InteractiveCommandSetIdString = "00B8868B-F9F5-4970-A048-410B05508506" -> string -const Microsoft.VisualStudio.InteractiveWindow.Shell.Guids.InteractiveToolWindowIdString = "2D0A56AA-9527-4B78-B6E6-EBE6E05DA749" -> string -const Microsoft.VisualStudio.InteractiveWindow.Shell.Guids.InteractiveWindowPackageIdString = "F5199A4E-6A60-4F79-82E9-FC92A41C4610" -> string -override Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Register(Microsoft.VisualStudio.Shell.RegistrationAttribute.RegistrationContext context) -> void -override Microsoft.VisualStudio.InteractiveWindow.Shell.ProvideInteractiveWindowAttribute.Unregister(Microsoft.VisualStudio.Shell.RegistrationAttribute.RegistrationContext context) -> void -static Microsoft.VisualStudio.VsInteractiveWindowExtensions.GetTextViewHost(this Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow window) -> Microsoft.VisualStudio.Text.Editor.IWpfTextViewHost -static Microsoft.VisualStudio.VsInteractiveWindowExtensions.SetLanguage(this Microsoft.VisualStudio.InteractiveWindow.IInteractiveWindow window, System.Guid languageServiceGuid, Microsoft.VisualStudio.Utilities.IContentType contentType) -> void -static readonly Microsoft.VisualStudio.InteractiveWindow.Shell.Guids.InteractiveCommandSetId -> System.Guid -static readonly Microsoft.VisualStudio.InteractiveWindow.Shell.Guids.InteractiveToolWindowId -> System.Guid -static readonly Microsoft.VisualStudio.InteractiveWindow.Shell.Guids.InteractiveWindowPackageId -> System.Guid diff --git a/src/InteractiveWindow/VisualStudio/PublicAPI.Unshipped.txt b/src/InteractiveWindow/VisualStudio/PublicAPI.Unshipped.txt deleted file mode 100644 index 5a1c8bf8b2462..0000000000000 --- a/src/InteractiveWindow/VisualStudio/PublicAPI.Unshipped.txt +++ /dev/null @@ -1,2 +0,0 @@ -*REMOVED*Microsoft.VisualStudio.InteractiveWindow.Shell.InteractiveWindowPackage -*REMOVED*Microsoft.VisualStudio.InteractiveWindow.Shell.InteractiveWindowPackage.InteractiveWindowPackage() -> void diff --git a/src/InteractiveWindow/VisualStudio/Resources/Package.ico b/src/InteractiveWindow/VisualStudio/Resources/Package.ico deleted file mode 100644 index ea3b23fe8d4b3..0000000000000 Binary files a/src/InteractiveWindow/VisualStudio/Resources/Package.ico and /dev/null differ diff --git a/src/InteractiveWindow/VisualStudio/VSInteractiveWindowResources.Designer.cs b/src/InteractiveWindow/VisualStudio/VSInteractiveWindowResources.Designer.cs deleted file mode 100644 index d6942f874e62f..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VSInteractiveWindowResources.Designer.cs +++ /dev/null @@ -1,63 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.18408 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.VisualStudio { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class VSInteractiveWindowResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal VSInteractiveWindowResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.VisualStudio.VSInteractiveWindowResources", typeof(VSInteractiveWindowResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - } -} diff --git a/src/InteractiveWindow/VisualStudio/VSInteractiveWindowResources.resx b/src/InteractiveWindow/VisualStudio/VSInteractiveWindowResources.resx deleted file mode 100644 index 4fdb1b6aff69b..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VSInteractiveWindowResources.resx +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 1.3 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/src/InteractiveWindow/VisualStudio/VSInteractiveWindowRules.ruleset b/src/InteractiveWindow/VisualStudio/VSInteractiveWindowRules.ruleset deleted file mode 100644 index e509683eb16a5..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VSInteractiveWindowRules.ruleset +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/InteractiveWindow/VisualStudio/VSPackage.resx b/src/InteractiveWindow/VisualStudio/VSPackage.resx deleted file mode 100644 index 4aaa53dfa23f8..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VSPackage.resx +++ /dev/null @@ -1,133 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Microsoft Visual Studio Interactive Window - - - Microsoft Visual Studio Interactive Window - - - Interactive Window - - - - Resources\Package.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - \ No newline at end of file diff --git a/src/InteractiveWindow/VisualStudio/VisualStudioInteractiveWindow.csproj b/src/InteractiveWindow/VisualStudio/VisualStudioInteractiveWindow.csproj deleted file mode 100644 index ef25d0642a873..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VisualStudioInteractiveWindow.csproj +++ /dev/null @@ -1,99 +0,0 @@ - - - - CSharp - - - - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} - {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - Microsoft.VisualStudio.InteractiveWindow.Shell - Microsoft.VisualStudio.VsInteractiveWindow - Program - $(DevEnvDir)devenv.exe - /rootsuffix RoslynDev /log - $(VisualStudioVersion) - true - RoslynDev - v4.6 - - - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - - - - - - - - - - - - - - - - - - - - - InternalUtilities\ExceptionUtilities.cs - - - InternalUtilities\FatalError.cs - - - - - - - - - - - - - - - - - - - True - True - VSInteractiveWindowResources.resx - - - Designer - - - - - ResXFileCodeGenerator - VSInteractiveWindowResources.Designer.cs - - - true - VSPackage - Designer - - - - - Menus.ctmenu - Designer - - - - - - - - - - diff --git a/src/InteractiveWindow/VisualStudio/VsInteractiveWindow.cs b/src/InteractiveWindow/VisualStudio/VsInteractiveWindow.cs deleted file mode 100644 index 38ceac62f5df6..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VsInteractiveWindow.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -// Dumps commands in QueryStatus and Exec. -// #define DUMP_COMMANDS - -using System; -using System.Runtime.InteropServices; -using System.Windows; -using System.Windows.Input; -using Microsoft.VisualStudio.ComponentModelHost; -using Microsoft.VisualStudio.Editor; -using Microsoft.VisualStudio.OLE.Interop; -using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.TextManager.Interop; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - /// - /// Default tool window for hosting interactive windows inside of Visual Studio. This hooks up support for - /// find in windows, forwarding commands down to the text view adapter, and providing access for setting - /// VS specific concepts (such as language service GUIDs) for the interactive window. - /// - /// Interactive windows can also be hosted outside of this tool window if the user creates an IInteractiveWindow - /// directly. In that case the user is responsible for doing what this class does themselves. But the - /// interactive window will be properly initialized for running inside of Visual Studio's process by our - /// VsInteractiveWindowEditorsFactoryService which handles all of the mapping of VS commands to API calls - /// on the interactive window. - /// - [Guid(Guids.InteractiveToolWindowIdString)] - internal sealed class VsInteractiveWindow : ToolWindowPane, IOleCommandTarget, IVsInteractiveWindow - { - // Keep in sync with Microsoft.VisualStudio.Editor.Implementation.EnableFindOptionDefinition.OptionName. - private const string EnableFindOptionName = "Enable Autonomous Find"; - - private readonly IComponentModel _componentModel; - private readonly IVsEditorAdaptersFactoryService _editorAdapters; - - private IInteractiveWindow _window; - private IVsFindTarget _findTarget; - private IOleCommandTarget _commandTarget; - private IInteractiveEvaluator _evaluator; - private IWpfTextViewHost _textViewHost; - - internal VsInteractiveWindow(IComponentModel model, Guid providerId, int instanceId, string title, IInteractiveEvaluator evaluator, __VSCREATETOOLWIN creationFlags) - { - _componentModel = model; - this.Caption = title; - _editorAdapters = _componentModel.GetService(); - _evaluator = evaluator; - - // The following calls this.OnCreate: - Guid clsId = this.ToolClsid; - Guid empty = Guid.Empty; - Guid typeId = providerId; - IVsWindowFrame frame; - var vsShell = (IVsUIShell)ServiceProvider.GlobalProvider.GetService(typeof(SVsUIShell)); - - // we don't pass __VSCREATETOOLWIN.CTW_fMultiInstance because multi instance panes are - // destroyed when closed. We are really multi instance but we don't want to be closed. - - ErrorHandler.ThrowOnFailure( - vsShell.CreateToolWindow( - (uint)(__VSCREATETOOLWIN.CTW_fInitNew | __VSCREATETOOLWIN.CTW_fToolbarHost | creationFlags), - (uint)instanceId, - this.GetIVsWindowPane(), - ref clsId, - ref typeId, - ref empty, - null, - title, - null, - out frame - ) - ); - var guid = GetType().GUID; - ErrorHandler.ThrowOnFailure(frame.SetGuidProperty((int)__VSFPROPID.VSFPROPID_CmdUIGuid, ref guid)); - this.Frame = frame; - } - - public void SetLanguage(Guid languageServiceGuid, IContentType contentType) - { - _window.SetLanguage(languageServiceGuid, contentType); - } - - public IInteractiveWindow InteractiveWindow { get { return _window; } } - - #region ToolWindowPane overrides - - protected override void OnCreate() - { - _window = _componentModel.GetService().CreateWindow(_evaluator); - _window.SubmissionBufferAdded += SubmissionBufferAdded; - _textViewHost = _window.GetTextViewHost(); - var textView = _textViewHost.TextView; - textView.Options.SetOptionValue(EnableFindOptionName, true); - var viewAdapter = _editorAdapters.GetViewAdapter(textView); - _findTarget = viewAdapter as IVsFindTarget; - _commandTarget = viewAdapter as IOleCommandTarget; - } - - private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e) - { - GetToolbarHost().ForceUpdateUI(); - } - - protected override void OnClose() - { - _window.Close(); - base.OnClose(); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (_window != null) - { - _window.Dispose(); - } - } - } - - /// - /// This property returns the control that should be hosted in the Tool Window. It can be - /// either a FrameworkElement (for easy creation of tool windows hosting WPF content), or it - /// can be an object implementing one of the IVsUIWPFElement or IVsUIWin32Element - /// interfaces. - /// - public override object Content - { - get { return _textViewHost; } - set { } - } - - public override void OnToolWindowCreated() - { - Guid commandUiGuid = VSConstants.GUID_TextEditorFactory; - ((IVsWindowFrame)Frame).SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref commandUiGuid); - - base.OnToolWindowCreated(); - - // add our toolbar which is defined in our VSCT file - var toolbarHost = GetToolbarHost(); - Guid guidInteractiveCmdSet = Guids.InteractiveCommandSetId; - ErrorHandler.ThrowOnFailure(toolbarHost.AddToolbar(VSTWT_LOCATION.VSTWT_TOP, ref guidInteractiveCmdSet, (uint)MenuIds.InteractiveWindowToolbar)); - } - - #endregion - - #region Window IOleCommandTarget - - public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) - { - return _commandTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); - } - - public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) - { - return _commandTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); - } - - #endregion - - #region IVsInteractiveWindow - - public void Show(bool focus) - { - var windowFrame = (IVsWindowFrame)Frame; - ErrorHandler.ThrowOnFailure(focus ? windowFrame.Show() : windowFrame.ShowNoActivate()); - - if (focus) - { - IInputElement input = _window.TextView as IInputElement; - if (input != null) - { - Keyboard.Focus(input); - } - } - } - - private IVsToolWindowToolbarHost GetToolbarHost() - { - var frame = (IVsWindowFrame)Frame; - object result; - ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_ToolbarHost, out result)); - return (IVsToolWindowToolbarHost)result; - } - - #endregion - } -} diff --git a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowCommandFilter.cs b/src/InteractiveWindow/VisualStudio/VsInteractiveWindowCommandFilter.cs deleted file mode 100644 index 75241adae1631..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowCommandFilter.cs +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -// Dumps commands in QueryStatus and Exec. -// #define DUMP_COMMANDS - -using System; -using System.Collections.Generic; -using Microsoft.VisualStudio.Editor; -using Microsoft.VisualStudio.OLE.Interop; -using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.TextManager.Interop; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - internal sealed class VsInteractiveWindowCommandFilter : IOleCommandTarget - { - // - // Command filter chain: - // *window* -> VsTextView -> ... -> *pre-language + the current language service's filter* -> editor services -> *preEditor* -> editor - // - private IOleCommandTarget _preLanguageCommandFilter; - private IOleCommandTarget _editorServicesCommandFilter; - private IOleCommandTarget _preEditorCommandFilter; - private IOleCommandTarget _editorCommandFilter; - // we route undo/redo commands to this target: - internal IOleCommandTarget currentBufferCommandHandler; - internal IOleCommandTarget firstLanguageServiceCommandFilter; - private readonly IInteractiveWindow _window; - internal readonly IVsTextView textViewAdapter; - private readonly IWpfTextViewHost _textViewHost; - internal readonly IEnumerable> _oleCommandTargetProviders; - internal readonly IContentTypeRegistryService _contentTypeRegistry; - - public VsInteractiveWindowCommandFilter(IVsEditorAdaptersFactoryService adapterFactory, IInteractiveWindow window, IVsTextView textViewAdapter, IVsTextBuffer bufferAdapter, IEnumerable> oleCommandTargetProviders, IContentTypeRegistryService contentTypeRegistry) - { - _window = window; - _oleCommandTargetProviders = oleCommandTargetProviders; - _contentTypeRegistry = contentTypeRegistry; - - this.textViewAdapter = textViewAdapter; - - // make us a code window so we'll have the same colors as a normal code window. - IVsTextEditorPropertyContainer propContainer; - ErrorHandler.ThrowOnFailure(((IVsTextEditorPropertyCategoryContainer)textViewAdapter).GetPropertyCategory(Microsoft.VisualStudio.Editor.DefGuidList.guidEditPropCategoryViewMasterSettings, out propContainer)); - propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewComposite_AllCodeWindowDefaults, true); - propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGlobalOpt_AutoScrollCaretOnTextEntry, true); - - // editor services are initialized in textViewAdapter.Initialize - hook underneath them: - _preEditorCommandFilter = new CommandFilter(this, CommandFilterLayer.PreEditor); - ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preEditorCommandFilter, out _editorCommandFilter)); - - textViewAdapter.Initialize( - (IVsTextLines)bufferAdapter, - IntPtr.Zero, - (uint)TextViewInitFlags.VIF_HSCROLL | (uint)TextViewInitFlags.VIF_VSCROLL | (uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT, - new[] { new INITVIEW { fSelectionMargin = 0, fWidgetMargin = 0, fVirtualSpace = 0, fDragDropMove = 1 } }); - - // disable change tracking because everything will be changed - var textViewHost = adapterFactory.GetWpfTextViewHost(textViewAdapter); - - _preLanguageCommandFilter = new CommandFilter(this, CommandFilterLayer.PreLanguage); - ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(_preLanguageCommandFilter, out _editorServicesCommandFilter)); - - _textViewHost = textViewHost; - } - - private IOleCommandTarget TextViewCommandFilterChain - { - get - { - // Non-character command processing starts with WindowFrame which calls ReplWindow.Exec. - // We need to invoke the view's Exec method in order to invoke its full command chain - // (features add their filters to the view). - return (IOleCommandTarget)textViewAdapter; - } - } - - #region IOleCommandTarget - - public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) - { - var nextTarget = TextViewCommandFilterChain; - - return nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); - } - - public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) - { - var nextTarget = TextViewCommandFilterChain; - - return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); - } - - #endregion - - public IWpfTextViewHost TextViewHost - { - get - { - return _textViewHost; - } - } - - private enum CommandFilterLayer - { - PreLanguage, - PreEditor - } - - private sealed class CommandFilter : IOleCommandTarget - { - private readonly VsInteractiveWindowCommandFilter _window; - private readonly CommandFilterLayer _layer; - - public CommandFilter(VsInteractiveWindowCommandFilter window, CommandFilterLayer layer) - { - _window = window; - _layer = layer; - } - - public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) - { - try - { - switch (_layer) - { - case CommandFilterLayer.PreLanguage: - return _window.PreLanguageCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); - - case CommandFilterLayer.PreEditor: - return _window.PreEditorCommandFilterQueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); - - default: - throw ExceptionUtilities.UnexpectedValue(_layer); - } - } - catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) - { - // Exceptions should not escape from command filters. - return _window._editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); - } - } - - public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) - { - try - { - switch (_layer) - { - case CommandFilterLayer.PreLanguage: - return _window.PreLanguageCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); - - case CommandFilterLayer.PreEditor: - return _window.PreEditorCommandFilterExec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); - - default: - throw ExceptionUtilities.UnexpectedValue(_layer); - } - } - catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) - { - // Exceptions should not escape from command filters. - return _window._editorCommandFilter.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); - } - } - } - - private int PreEditorCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) - { - if (pguidCmdGroup == Guids.InteractiveCommandSetId) - { - switch ((CommandIds)prgCmds[0].cmdID) - { - case CommandIds.BreakLine: - prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled; - prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; - return VSConstants.S_OK; - } - } - else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) - { - switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID) - { - // TODO: Add support of rotating clipboard ring - // https://github.com/dotnet/roslyn/issues/5651 - case VSConstants.VSStd97CmdID.PasteNextTBXCBItem: - prgCmds[0].cmdf = CommandDisabled; - return VSConstants.S_OK; - } - } - - return _editorCommandFilter.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); - } - - private int PreEditorCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) - { - var nextTarget = _editorCommandFilter; - - if (pguidCmdGroup == Guids.InteractiveCommandSetId) - { - switch ((CommandIds)nCmdID) - { - case CommandIds.BreakLine: - if (_window.Operations.BreakLine()) - { - return VSConstants.S_OK; - } - break; - } - } - else if (pguidCmdGroup == VSConstants.VSStd2K) - { - switch ((VSConstants.VSStd2KCmdID)nCmdID) - { - case VSConstants.VSStd2KCmdID.TYPECHAR: - { - var operations = _window.Operations as IInteractiveWindowOperations2; - if (operations != null) - { - char typedChar = (char)(ushort)System.Runtime.InteropServices.Marshal.GetObjectForNativeVariant(pvaIn); - operations.TypeChar(typedChar); - return VSConstants.S_OK; - } - else - { - _window.Operations.Delete(); - } - break; - } - - case VSConstants.VSStd2KCmdID.RETURN: - if (_window.Operations.Return()) - { - return VSConstants.S_OK; - } - break; - - // TODO: - //case VSConstants.VSStd2KCmdID.DELETEWORDLEFT: - //case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT: - // break; - - case VSConstants.VSStd2KCmdID.BACKSPACE: - _window.Operations.Backspace(); - return VSConstants.S_OK; - - case VSConstants.VSStd2KCmdID.UP: - - if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown) - { - _window.Operations.HistoryPrevious(); - return VSConstants.S_OK; - } - break; - - case VSConstants.VSStd2KCmdID.DOWN: - if (_window.CurrentLanguageBuffer != null && !_window.IsRunning && CaretAtEnd && UseSmartUpDown) - { - _window.Operations.HistoryNext(); - return VSConstants.S_OK; - } - break; - - case VSConstants.VSStd2KCmdID.CANCEL: - if (_window.TextView.Selection.IsEmpty) - { - _window.Operations.Cancel(); - } - break; - - case VSConstants.VSStd2KCmdID.BOL: - _window.Operations.Home(false); - return VSConstants.S_OK; - - case VSConstants.VSStd2KCmdID.BOL_EXT: - _window.Operations.Home(true); - return VSConstants.S_OK; - - case VSConstants.VSStd2KCmdID.EOL: - _window.Operations.End(false); - return VSConstants.S_OK; - - case VSConstants.VSStd2KCmdID.EOL_EXT: - _window.Operations.End(true); - return VSConstants.S_OK; - case VSConstants.VSStd2KCmdID.CUTLINE: - { - var operations = _window.Operations as IInteractiveWindowOperations2; - if (operations != null) - { - operations.CutLine(); - return VSConstants.S_OK; - } - } - break; - case VSConstants.VSStd2KCmdID.DELETELINE: - { - var operations = _window.Operations as IInteractiveWindowOperations2; - if (operations != null) - { - operations.DeleteLine(); - return VSConstants.S_OK; - } - } - break; - } - } - else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) - { - switch ((VSConstants.VSStd97CmdID)nCmdID) - { - // TODO: Add support of rotating clipboard ring - // https://github.com/dotnet/roslyn/issues/5651 - case VSConstants.VSStd97CmdID.PasteNextTBXCBItem: - return (int)OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED; - - case VSConstants.VSStd97CmdID.Paste: - _window.Operations.Paste(); - return VSConstants.S_OK; - - case VSConstants.VSStd97CmdID.Cut: - _window.Operations.Cut(); - return VSConstants.S_OK; - - case VSConstants.VSStd97CmdID.Copy: - { - var operations = _window.Operations as IInteractiveWindowOperations2; - if (operations != null) - { - operations.Copy(); - return VSConstants.S_OK; - } - } - break; - - case VSConstants.VSStd97CmdID.Delete: - _window.Operations.Delete(); - return VSConstants.S_OK; - - case VSConstants.VSStd97CmdID.SelectAll: - _window.Operations.SelectAll(); - return VSConstants.S_OK; - } - } - - return nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); - } - - private int PreLanguageCommandFilterQueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) - { - var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter; - - if (pguidCmdGroup == Guids.InteractiveCommandSetId) - { - switch ((CommandIds)prgCmds[0].cmdID) - { - case CommandIds.HistoryNext: - case CommandIds.HistoryPrevious: - case CommandIds.SearchHistoryNext: - case CommandIds.SearchHistoryPrevious: - case CommandIds.SmartExecute: - // TODO: Submit? - prgCmds[0].cmdf = _window.CurrentLanguageBuffer != null ? CommandEnabled : CommandDisabled; - prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; - return VSConstants.S_OK; - case CommandIds.AbortExecution: - prgCmds[0].cmdf = _window.IsRunning ? CommandEnabled : CommandDisabled; - prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; - return VSConstants.S_OK; - case CommandIds.Reset: - prgCmds[0].cmdf = !_window.IsResetting ? CommandEnabled : CommandDisabled; - prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; - return VSConstants.S_OK; - case CommandIds.CopyCode: - prgCmds[0].cmdf = _window.Operations is IInteractiveWindowOperations2 ? CommandEnabled : CommandDisabled; - return VSConstants.S_OK; - default: - prgCmds[0].cmdf = CommandEnabled; - break; - } - prgCmds[0].cmdf |= (uint)OLECMDF.OLECMDF_DEFHIDEONCTXTMENU; - } - else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) - { - // undo/redo support: - switch ((VSConstants.VSStd97CmdID)prgCmds[0].cmdID) - { - case VSConstants.VSStd97CmdID.Undo: - case VSConstants.VSStd97CmdID.MultiLevelUndo: - case VSConstants.VSStd97CmdID.MultiLevelUndoList: - case VSConstants.VSStd97CmdID.Redo: - case VSConstants.VSStd97CmdID.MultiLevelRedo: - case VSConstants.VSStd97CmdID.MultiLevelRedoList: - return currentBufferCommandHandler.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); - } - } - - if (nextTarget != null) - { - var result = nextTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); -#if DUMP_COMMANDS - //DumpCmd("QS", result, ref pguidCmdGroup, prgCmds[0].cmdID, prgCmds[0].cmdf); -#endif - return result; - } - return VSConstants.E_FAIL; - } - - private int PreLanguageCommandFilterExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) - { - var nextTarget = firstLanguageServiceCommandFilter ?? _editorServicesCommandFilter; - - if (pguidCmdGroup == Guids.InteractiveCommandSetId) - { - switch ((CommandIds)nCmdID) - { - case CommandIds.AbortExecution: _window.Evaluator.AbortExecution(); return VSConstants.S_OK; - case CommandIds.Reset: _window.Operations.ResetAsync(); return VSConstants.S_OK; - case CommandIds.SmartExecute: _window.Operations.ExecuteInput(); return VSConstants.S_OK; - case CommandIds.HistoryNext: _window.Operations.HistoryNext(); return VSConstants.S_OK; - case CommandIds.HistoryPrevious: _window.Operations.HistoryPrevious(); return VSConstants.S_OK; - case CommandIds.ClearScreen: _window.Operations.ClearView(); return VSConstants.S_OK; - case CommandIds.CopyCode: - { - var operation = _window.Operations as IInteractiveWindowOperations2; - if (operation != null) - { - operation.CopyCode(); - } - return VSConstants.S_OK; - } - case CommandIds.SearchHistoryNext: - _window.Operations.HistorySearchNext(); - return VSConstants.S_OK; - case CommandIds.SearchHistoryPrevious: - _window.Operations.HistorySearchPrevious(); - return VSConstants.S_OK; - } - } - else if (pguidCmdGroup == VSConstants.VSStd2K) - { - switch ((VSConstants.VSStd2KCmdID)nCmdID) - { - case VSConstants.VSStd2KCmdID.RETURN: - if (_window.Operations.TrySubmitStandardInput()) - { - return VSConstants.S_OK; - } - break; - - case VSConstants.VSStd2KCmdID.SHOWCONTEXTMENU: - ShowContextMenu(); - return VSConstants.S_OK; - } - } - else if (currentBufferCommandHandler != null && pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) - { - // undo/redo support: - switch ((VSConstants.VSStd97CmdID)nCmdID) - { - // TODO: remove (https://github.com/dotnet/roslyn/issues/5642) - case VSConstants.VSStd97CmdID.FindReferences: - return VSConstants.S_OK; - case VSConstants.VSStd97CmdID.Undo: - case VSConstants.VSStd97CmdID.MultiLevelUndo: - case VSConstants.VSStd97CmdID.MultiLevelUndoList: - case VSConstants.VSStd97CmdID.Redo: - case VSConstants.VSStd97CmdID.MultiLevelRedo: - case VSConstants.VSStd97CmdID.MultiLevelRedoList: - return currentBufferCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); - } - } - - int res = nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); -#if DUMP_COMMANDS - DumpCmd("Exec", result, ref pguidCmdGroup, nCmdID, 0); -#endif - return res; - } - - private void ShowContextMenu() - { - var uishell = (IVsUIShell)InteractiveWindowPackage.GetGlobalService(typeof(SVsUIShell)); - if (uishell != null) - { - var pt = System.Windows.Forms.Cursor.Position; - var position = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } }; - var guid = Guids.InteractiveCommandSetId; - ErrorHandler.ThrowOnFailure(uishell.ShowContextMenu(0, ref guid, (int)MenuIds.InteractiveWindowContextMenu, position, this)); - } - } - - private const uint CommandEnabled = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); - private const uint CommandDisabled = (uint)(OLECMDF.OLECMDF_SUPPORTED); - private const uint CommandDisabledAndHidden = (uint)(OLECMDF.OLECMDF_INVISIBLE | OLECMDF.OLECMDF_SUPPORTED); - - private bool CaretAtEnd - { - get - { - var caret = _window.TextView.Caret; - return caret.Position.BufferPosition.Position == caret.Position.BufferPosition.Snapshot.Length; - } - } - - private bool UseSmartUpDown - { - get - { - return _window.TextView.Options.GetOptionValue(InteractiveWindowOptions.SmartUpDown); - } - } - - public IOleCommandTarget EditorServicesCommandFilter - { - get - { - return _editorServicesCommandFilter; - } - } - } -} diff --git a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowEditorFactoryService.cs b/src/InteractiveWindow/VisualStudio/VsInteractiveWindowEditorFactoryService.cs deleted file mode 100644 index 3110dcc737b3c..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowEditorFactoryService.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Composition; -using System.Windows; -using System.Windows.Threading; -using Microsoft.VisualStudio.Editor; -using Microsoft.VisualStudio.OLE.Interop; -using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.TextManager.Interop; -using Microsoft.VisualStudio.Utilities; -using Microsoft.VisualStudio.InteractiveWindow; -using Microsoft.VisualStudio.InteractiveWindow.Shell; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; - - [Export(typeof(IInteractiveWindowEditorFactoryService))] - internal sealed class VsInteractiveWindowEditorFactoryService : IInteractiveWindowEditorFactoryService - { - private readonly IOleServiceProvider _provider; - private readonly IVsEditorAdaptersFactoryService _adapterFactory; - private readonly IContentTypeRegistryService _contentTypeRegistry; - private readonly IEnumerable> _oleCommandTargetProviders; - - [ImportingConstructor] - public VsInteractiveWindowEditorFactoryService(IVsEditorAdaptersFactoryService adaptersFactory, IContentTypeRegistryService contentTypeRegistry, [ImportMany]IEnumerable> oleCommandTargetProviders) - { - _adapterFactory = adaptersFactory; - _provider = (IOleServiceProvider)InteractiveWindowPackage.GetGlobalService(typeof(IOleServiceProvider)); - _contentTypeRegistry = contentTypeRegistry; - _oleCommandTargetProviders = oleCommandTargetProviders; - } - - IWpfTextView IInteractiveWindowEditorFactoryService.CreateTextView(IInteractiveWindow window, ITextBuffer buffer, ITextViewRoleSet roles) - { - var bufferAdapter = _adapterFactory.CreateVsTextBufferAdapterForSecondaryBuffer(_provider, buffer); - - // Create and initialize text view adapter. - // WARNING: This might trigger various services like IntelliSense, margins, taggers, etc. - var textViewAdapter = _adapterFactory.CreateVsTextViewAdapter(_provider, roles); - - var commandFilter = new VsInteractiveWindowCommandFilter(_adapterFactory, window, textViewAdapter, bufferAdapter, _oleCommandTargetProviders, _contentTypeRegistry); - window.Properties[typeof(VsInteractiveWindowCommandFilter)] = commandFilter; - return commandFilter.TextViewHost.TextView; - } - - ITextBuffer IInteractiveWindowEditorFactoryService.CreateAndActivateBuffer(IInteractiveWindow window) - { - // create buffer adapter to support undo/redo: - IContentType contentType; - if (!window.Properties.TryGetProperty(typeof(IContentType), out contentType)) - { - contentType = _contentTypeRegistry.GetContentType("text"); - } - - var bufferAdapter = _adapterFactory.CreateVsTextBufferAdapter(_provider, contentType); - bufferAdapter.InitializeContent("", 0); - - var commandFilter = GetCommandFilter(window); - if (commandFilter.currentBufferCommandHandler != null) - { - ((IVsPersistDocData)commandFilter.currentBufferCommandHandler).Close(); - } - - commandFilter.currentBufferCommandHandler = (IOleCommandTarget)bufferAdapter; - - return _adapterFactory.GetDocumentBuffer(bufferAdapter); - } - - internal static void SetEditorOptions(IEditorOptions options, Guid languageServiceGuid) - { - IVsTextManager textMgr = (IVsTextManager)InteractiveWindowPackage.GetGlobalService(typeof(SVsTextManager)); - var langPrefs = new LANGPREFERENCES[1]; - langPrefs[0].guidLang = languageServiceGuid; - ErrorHandler.ThrowOnFailure(textMgr.GetUserPreferences(null, null, langPrefs, null)); - - options.SetOptionValue(DefaultTextViewHostOptions.ChangeTrackingId, false); - options.SetOptionValue(DefaultOptions.ConvertTabsToSpacesOptionId, langPrefs[0].fInsertTabs == 0); - options.SetOptionValue(DefaultOptions.TabSizeOptionId, (int)langPrefs[0].uTabSize); - options.SetOptionValue(DefaultOptions.IndentSizeOptionId, (int)langPrefs[0].uIndentSize); - } - - internal static Dispatcher GetDispatcher(IInteractiveWindow window) - { - return ((FrameworkElement)window.TextView).Dispatcher; - } - - internal static VsInteractiveWindowCommandFilter GetCommandFilter(IInteractiveWindow window) - { - return (VsInteractiveWindowCommandFilter)window.Properties[typeof(VsInteractiveWindowCommandFilter)]; - } - } -} diff --git a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowExtensions.cs b/src/InteractiveWindow/VisualStudio/VsInteractiveWindowExtensions.cs deleted file mode 100644 index b88f985e54c20..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowExtensions.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.VisualStudio.InteractiveWindow; -using Microsoft.VisualStudio.InteractiveWindow.Shell; -using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.Text.Editor; -using Microsoft.VisualStudio.TextManager.Interop; -using Microsoft.VisualStudio.Utilities; - -namespace Microsoft.VisualStudio -{ - public static class VsInteractiveWindowExtensions - { - public static IWpfTextViewHost GetTextViewHost(this IInteractiveWindow window) - { - var cmdFilter = VsInteractiveWindowEditorFactoryService.GetCommandFilter(window); - if (cmdFilter != null) - { - return cmdFilter.TextViewHost; - } - return null; - } - - public static void SetLanguage(this IInteractiveWindow window, Guid languageServiceGuid, IContentType contentType) - { - VsInteractiveWindowEditorFactoryService.GetDispatcher(window).CheckAccess(); - - var commandFilter = VsInteractiveWindowEditorFactoryService.GetCommandFilter(window); - window.Properties[typeof(IContentType)] = contentType; - commandFilter.firstLanguageServiceCommandFilter = null; - var provider = commandFilter._oleCommandTargetProviders.OfContentType(contentType, commandFilter._contentTypeRegistry); - if (provider != null) - { - var targetFilter = commandFilter.firstLanguageServiceCommandFilter ?? commandFilter.EditorServicesCommandFilter; - var target = provider.GetCommandTarget(window.TextView, targetFilter); - if (target != null) - { - commandFilter.firstLanguageServiceCommandFilter = target; - } - } - - if (window.CurrentLanguageBuffer != null) - { - window.CurrentLanguageBuffer.ChangeContentType(contentType, null); - } - - VsInteractiveWindowEditorFactoryService.SetEditorOptions(window.TextView.Options, languageServiceGuid); - } - } -} diff --git a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowFactory.cs b/src/InteractiveWindow/VisualStudio/VsInteractiveWindowFactory.cs deleted file mode 100644 index ffab15287000e..0000000000000 --- a/src/InteractiveWindow/VisualStudio/VsInteractiveWindowFactory.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.ComponentModelHost; -using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.InteractiveWindow; - -namespace Microsoft.VisualStudio.InteractiveWindow.Shell -{ - [Export(typeof(IVsInteractiveWindowFactory))] - internal sealed class VsInteractiveWindowFactory : IVsInteractiveWindowFactory - { - private readonly IComponentModel _componentModel; - - [ImportingConstructor] - internal VsInteractiveWindowFactory(SVsServiceProvider serviceProvider) - { - _componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); - } - - public IVsInteractiveWindow Create(Guid providerId, int instanceId, string title, IInteractiveEvaluator evaluator, __VSCREATETOOLWIN creationFlags) - { - return new VsInteractiveWindow(_componentModel, providerId, instanceId, title, evaluator, creationFlags); - } - } -} diff --git a/src/InteractiveWindow/VisualStudio/project.json b/src/InteractiveWindow/VisualStudio/project.json deleted file mode 100644 index 17e2160d28e2a..0000000000000 --- a/src/InteractiveWindow/VisualStudio/project.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "dependencies": { - "RoslynDependencies.Microsoft.VisualStudio.ComponentModelHost": "14.3.25407", - "Microsoft.VisualStudio.Designer.Interfaces": "1.1.4322", - "Microsoft.VisualStudio.ImageCatalog": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.OLE.Interop": "7.10.6070", - "Microsoft.VisualStudio.Shell.Interop.10.0": "10.0.30319", - "Microsoft.VisualStudio.Shell.Interop.11.0": "11.0.61030", - "Microsoft.VisualStudio.Shell.Interop.12.1.DesignTime": "12.1.30328", - "Microsoft.VisualStudio.TextManager.Interop.10.0": "10.0.30319", - "Microsoft.VisualStudio.TextManager.Interop.12.0": "12.0.30110", - "Microsoft.VisualStudio.TextManager.Interop.12.1.DesignTime": "12.1.30328", - "Microsoft.VisualStudio.SDK.EmbedInteropTypes": "14.1.2", - "Microsoft.VisualStudio.ManagedInterfaces": "8.0.50727", - "Microsoft.VisualStudio.WCFReference.Interop": "9.0.30729", - "Microsoft.VisualStudio.Data.Core": "9.0.21022", - "Microsoft.VisualStudio.Data.Services": "9.0.21022", - "Microsoft.VisualStudio.Editor": { - "version": "14.3.25407", - "suppressParent": "all" - }, - "Microsoft.VisualStudio.Shell.14.0": { - "version": "14.3.25407", - "suppressParent": "all" - } - }, - "frameworks": { - "net46": { } - }, - "runtimes": { - "win7": { } - } -} \ No newline at end of file diff --git a/src/InteractiveWindow/VisualStudio/source.extension.vsixmanifest b/src/InteractiveWindow/VisualStudio/source.extension.vsixmanifest deleted file mode 100644 index 859e7ce1fb04e..0000000000000 --- a/src/InteractiveWindow/VisualStudio/source.extension.vsixmanifest +++ /dev/null @@ -1,31 +0,0 @@ - - - - - VisualStudio Interactive Window - Interactive components for Visual Studio. - ..\CommonExtensions\Microsoft\VisualStudioInteractiveWindow - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Setup/Deployment/Current/Roslyn.Deployment.Full.csproj b/src/Setup/Deployment/Current/Roslyn.Deployment.Full.csproj index 446a3f11a369c..1a379fb5e2fab 100644 --- a/src/Setup/Deployment/Current/Roslyn.Deployment.Full.csproj +++ b/src/Setup/Deployment/Current/Roslyn.Deployment.Full.csproj @@ -48,13 +48,6 @@ false VSIXContainerProjectOutputGroup%3b - - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} - VisualStudioInteractiveWindow - Vsixes - false - VSIXContainerProjectOutputGroup%3b - {C467FEFA-337D-4705-BB5A-BDF41A555FDC} VisualStudioSetupInteractive diff --git a/src/Setup/Deployment/Current/source.extension.vsixmanifest b/src/Setup/Deployment/Current/source.extension.vsixmanifest index 4121d9a6aec16..19e53f298678d 100644 --- a/src/Setup/Deployment/Current/source.extension.vsixmanifest +++ b/src/Setup/Deployment/Current/source.extension.vsixmanifest @@ -29,15 +29,6 @@ Location="|VisualStudioSetup;VSIXContainerProjectOutputGroup|" Id="|VisualStudioSetup;VSIXIdentifierProjectOutputGroup|" /> - - false VSIXContainerProjectOutputGroup%3b - - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} - VisualStudioInteractiveWindow - Vsixes - false - VSIXContainerProjectOutputGroup%3b - {C467FEFA-337D-4705-BB5A-BDF41A555FDC} VisualStudioSetupInteractive diff --git a/src/Setup/Deployment/Next/source.extension.vsixmanifest b/src/Setup/Deployment/Next/source.extension.vsixmanifest index 577e272820c43..547b4b3bf1110 100644 --- a/src/Setup/Deployment/Next/source.extension.vsixmanifest +++ b/src/Setup/Deployment/Next/source.extension.vsixmanifest @@ -38,15 +38,6 @@ Location="|VisualStudioSetup.Next;VSIXContainerProjectOutputGroup|" Id="|VisualStudioSetup.Next;VSIXIdentifierProjectOutputGroup|" /> - - 5 Then - Console.WriteLine("Expected arguments: ") + If args.Length <> 4 Then + Console.WriteLine("Expected arguments: ") Return 1 End If @@ -146,7 +144,6 @@ Public Class BuildDevDivInsertionFiles "Roslyn.VisualStudio.Setup.vsix", "ExpressionEvaluatorPackage.vsix", "Roslyn.VisualStudio.InteractiveComponents.vsix", - "Microsoft.VisualStudio.VsInteractiveWindow.vsix", "Roslyn.VisualStudio.Setup.Interactive.vsix", "Roslyn.VisualStudio.Setup.Next.vsix" } @@ -498,13 +495,6 @@ Public Class BuildDevDivInsertionFiles Me.IsFacade = isFacade End Sub - ' TODO: remove - Public ReadOnly Property IsInteractiveWindow As Boolean - Get - Return PackageName = "Microsoft.VisualStudio.InteractiveWindow" - End Get - End Property - ' TODO: remove (https://github.com/dotnet/roslyn/issues/13204) ' Don't update CoreXT incompatible packages. They are inserted manually until CoreXT updates to NuGet 3.5 RTM. Public ReadOnly Property IsCoreXTCompatible As Boolean @@ -584,10 +574,6 @@ Public Class BuildDevDivInsertionFiles Next Next - ' TODO: remove once we have a proper package - result.Add("Microsoft.VisualStudio.InteractiveWindow.dll", New DependencyInfo("lib\net46", "lib\net46", "Microsoft.VisualStudio.InteractiveWindow", _interactiveWindowPackageVersion, isNative:=False, isFacade:=False)) - result.Add("Microsoft.VisualStudio.VsInteractiveWindow.dll", New DependencyInfo("lib\net46", "lib\net46", "Microsoft.VisualStudio.InteractiveWindow", _interactiveWindowPackageVersion, isNative:=False, isFacade:=False)) - Return result End Function @@ -637,15 +623,11 @@ Public Class BuildDevDivInsertionFiles If Not dependency.IsNative Then Dim version As Version - If dependency.IsInteractiveWindow Then - version = Version.Parse(_interactiveWindowPackageVersion.Split("-"c)(0)) - Else - Dim dllPath = Path.Combine(_nugetPackageRoot, dependency.PackageName, dependency.PackageVersion, dependency.ImplementationDir, fileName) - - Using peReader = New PEReader(File.OpenRead(dllPath)) - version = peReader.GetMetadataReader().GetAssemblyDefinition().Version - End Using - End If + Dim dllPath = Path.Combine(_nugetPackageRoot, dependency.PackageName, dependency.PackageVersion, dependency.ImplementationDir, fileName) + + Using peReader = New PEReader(File.OpenRead(dllPath)) + version = peReader.GetMetadataReader().GetAssemblyDefinition().Version + End Using writer.WriteLine($"{Path.GetFileNameWithoutExtension(fileName)},{version}") End If @@ -655,10 +637,6 @@ Public Class BuildDevDivInsertionFiles Private Sub CopyDependencies(dependencies As IReadOnlyDictionary(Of String, DependencyInfo)) For Each dependency In dependencies.Values - If dependency.IsInteractiveWindow Then - Continue For - End If - ' TODO: remove (https://github.com/dotnet/roslyn/issues/13204) ' Don't update CoreXT incompatible packages. They are inserted manually until CoreXT updates to NuGet 3.5 RTM. If Not dependency.IsCoreXTCompatible Then diff --git a/src/Setup/DevDivPackages/Dependencies.proj b/src/Setup/DevDivPackages/Dependencies.proj deleted file mode 100644 index c1c00de85d214..0000000000000 --- a/src/Setup/DevDivPackages/Dependencies.proj +++ /dev/null @@ -1,33 +0,0 @@ - - - - - $(OutDir)DevDivPackages - - - - - $(MicrosoftVisualStudioInteractiveWindowVersion)-beta-$(BuildNumberFiveDigitDateStamp)-$(BuildNumberBuildOfTheDayPadded) - false - ManagedDependencies - - - - - - $(NuGetPackageRoot)\%(NuSpec.Identity)\%(NuSpec.Version) - $(OutDir)\ - - - - - - - - - - - diff --git a/src/Setup/DevDivPackages/Roslyn/project.json b/src/Setup/DevDivPackages/Roslyn/project.json index ec06e87295db2..78165f01b38c9 100644 --- a/src/Setup/DevDivPackages/Roslyn/project.json +++ b/src/Setup/DevDivPackages/Roslyn/project.json @@ -6,6 +6,8 @@ "System.Collections.Immutable": "1.2.0", "System.Reflection.Metadata": "1.4.1-beta-24430-01", "ManagedEsent": "1.9.4", + "Microsoft.VisualStudio.InteractiveWindow": "2.0.0-beta5-60820-04", + "Microsoft.VisualStudio.VsInteractiveWindow": "2.0.0-beta5-60820-04", "System.AppContext": "4.1.0", "System.Console": "4.0.0", "System.Collections": "4.0.11", diff --git a/src/Setup/DevDivPackages/VS.ExternalAPIs.Microsoft.VisualStudio.InteractiveWindow.nuspec b/src/Setup/DevDivPackages/VS.ExternalAPIs.Microsoft.VisualStudio.InteractiveWindow.nuspec deleted file mode 100644 index da4bdfb35783d..0000000000000 --- a/src/Setup/DevDivPackages/VS.ExternalAPIs.Microsoft.VisualStudio.InteractiveWindow.nuspec +++ /dev/null @@ -1,14 +0,0 @@ - - - - VS.ExternalAPIs.Microsoft.VisualStudio.InteractiveWindow - CoreXT package for the VS build. - CoreXT package for the VS build. - Managed Languages - 0.0 - - - - - - diff --git a/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/Microsoft.CodeAnalysis.LanguageServices.vsmanproj b/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/Microsoft.CodeAnalysis.LanguageServices.vsmanproj index 87afc6cc4b8e8..352afafab2106 100644 --- a/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/Microsoft.CodeAnalysis.LanguageServices.vsmanproj +++ b/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/Microsoft.CodeAnalysis.LanguageServices.vsmanproj @@ -13,10 +13,6 @@ - - - - @@ -31,6 +27,5 @@ - diff --git a/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioInteractiveComponents/Microsoft.CodeAnalysis.VisualStudioInteractiveComponents.swr b/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioInteractiveComponents/Microsoft.CodeAnalysis.VisualStudioInteractiveComponents.swr index 417ed78bba16b..6ea1784f561ae 100644 --- a/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioInteractiveComponents/Microsoft.CodeAnalysis.VisualStudioInteractiveComponents.swr +++ b/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioInteractiveComponents/Microsoft.CodeAnalysis.VisualStudioInteractiveComponents.swr @@ -18,6 +18,3 @@ vs.dependencies vs.dependency id=Microsoft.CodeAnalysis.VisualStudio.Setup version=$(Version) type=Required - vs.dependency id=Microsoft.VisualStudio.InteractiveWindow - version=$(Version) - type=Required diff --git a/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioSetupInteractive/Microsoft.CodeAnalysis.VisualStudio.Setup.Interactive.swr b/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioSetupInteractive/Microsoft.CodeAnalysis.VisualStudio.Setup.Interactive.swr index 7c89548bddbfa..02933c03b2503 100644 --- a/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioSetupInteractive/Microsoft.CodeAnalysis.VisualStudio.Setup.Interactive.swr +++ b/src/Setup/DevDivVsix/MicrosoftCodeAnalysisLanguageServices/MicrosoftCodeAnalysisVisualStudioSetupInteractive/Microsoft.CodeAnalysis.VisualStudio.Setup.Interactive.swr @@ -21,6 +21,3 @@ vs.dependencies vs.dependency id=Microsoft.CodeAnalysis.VisualStudio.InteractiveComponents version=$(Version) type=Required - vs.dependency id=Microsoft.VisualStudio.InteractiveWindow - version=$(Version) - type=Required diff --git a/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.swixproj b/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.swixproj deleted file mode 100644 index 4d849dee3facc..0000000000000 --- a/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.swixproj +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - neutral - false - $(OutDir)Insertion - manifest - - - - - - $(PackagePreprocessorDefinitions);Version=$(VsixVersion);OutputPath=$(OutDir);LicenseUri=http://www.microsoft.com - $(BaseIntermediateOutputPath)$(Configuration)\ - - - - - - - - diff --git a/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.swr b/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.swr deleted file mode 100644 index 598751c5d873a..0000000000000 --- a/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.swr +++ /dev/null @@ -1,15 +0,0 @@ -use vs - -package name=Microsoft.VisualStudio.InteractiveWindow - version=$(Version) - vs.package.type=vsix - vs.package.vsixId=1F42C6D0-F876-4AF0-8185-1BEB0A325BB2 - vs.package.installSize=253952 - -vs.localizedResources - vs.localizedResource language=en-us - title="VisualStudio Interactive Components" - description="Interactive components for Visual Studio." - -vs.payloads - vs.payload source=$(OutputPath)Microsoft.VisualStudio.VsInteractiveWindow.vsix diff --git a/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.vsmanproj b/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.vsmanproj deleted file mode 100644 index 786acfb18d8b4..0000000000000 --- a/src/Setup/DevDivVsix/MicrosoftVisualStudioInteractiveWindow/Microsoft.VisualStudio.InteractiveWindow.vsmanproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - true - true - Debug - $(OutDir)Insertion - true - - - - - - - - - - - - - diff --git a/src/Setup/SetupStep2.proj b/src/Setup/SetupStep2.proj index b29bd22d89e4f..c52f279cec878 100644 --- a/src/Setup/SetupStep2.proj +++ b/src/Setup/SetupStep2.proj @@ -7,8 +7,7 @@ - - + diff --git a/src/VisualStudio/CSharp/Repl/CSharpVisualStudioRepl.csproj b/src/VisualStudio/CSharp/Repl/CSharpVisualStudioRepl.csproj index f5db7412e879d..8ae42074377c3 100644 --- a/src/VisualStudio/CSharp/Repl/CSharpVisualStudioRepl.csproj +++ b/src/VisualStudio/CSharp/Repl/CSharpVisualStudioRepl.csproj @@ -44,10 +44,6 @@ {8E2A252E-A140-45A6-A81A-2652996EA589} InteractiveFeatures - - {01e9bd68-0339-4a13-b42f-a3ca84d164f3} - InteractiveWindow - {86fd5b9a-4fa0-4b10-b59f-cfaf077a859c} ServicesVisualStudio @@ -61,10 +57,6 @@ {a31228bb-f05c-4d4a-b98a-0e681d876b7c} VisualStudioInteractiveServices - - {20bb6fac-44d2-4d76-abfe-0c1e163a1a4f} - VisualStudioInteractiveWindow - diff --git a/src/VisualStudio/CSharp/Test/CSharpVisualStudioTest.csproj b/src/VisualStudio/CSharp/Test/CSharpVisualStudioTest.csproj index a2f8108c4a625..127692d41e2d5 100644 --- a/src/VisualStudio/CSharp/Test/CSharpVisualStudioTest.csproj +++ b/src/VisualStudio/CSharp/Test/CSharpVisualStudioTest.csproj @@ -50,10 +50,6 @@ {3CDEEAB7-2256-418A-BEB2-620B5CB16302} EditorFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - {8CEE3609-A5A9-4A9B-86D7-33118F5D6B33} EditorServicesTest @@ -74,10 +70,6 @@ {A1455D30-55FC-45EF-8759-3AEBDB13D940} ServicesVisualStudioTest - - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} - VisualStudioInteractiveWindow - {5DEFADBD-44EB-47A2-A53E-F1282CC9E4E9} CSharpVisualStudio diff --git a/src/VisualStudio/CSharp/Test/project.json b/src/VisualStudio/CSharp/Test/project.json index d5f3c2e9219d8..c66b62a9318a4 100644 --- a/src/VisualStudio/CSharp/Test/project.json +++ b/src/VisualStudio/CSharp/Test/project.json @@ -1,5 +1,9 @@ { "dependencies": { + "Microsoft.VisualStudio.InteractiveWindow": { + "version": "2.0.0-beta5-60820-04", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Text.UI": { "version": "14.3.25407", "suppressParent": "all" @@ -8,6 +12,14 @@ "version": "14.3.25407", "suppressParent": "all" }, + "Microsoft.VisualStudio.Language.StandardClassification": { + "version": "14.3.25407", + "suppressParent": "all" + }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal" : { + "version": "14.3.25407", + "suppressParent": "all" + } }, "frameworks": { "net46": { } diff --git a/src/VisualStudio/Core/Def/project.json b/src/VisualStudio/Core/Def/project.json index afd6534614254..786c7e19fb4cf 100644 --- a/src/VisualStudio/Core/Def/project.json +++ b/src/VisualStudio/Core/Def/project.json @@ -18,10 +18,18 @@ "version": "14.3.25407", "suppressParent": "all" }, + "Microsoft.VisualStudio.Language.StandardClassification": { + "version": "14.3.25407", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Language.Intellisense": { "version": "14.3.25407", "suppressParent": "all" }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal" : { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.Internal.VisualStudio.Shell.Interop.14.0.DesignTime": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/VisualStudio/Core/Test/project.json b/src/VisualStudio/Core/Test/project.json index 82f86b4d731e7..74c9fa57be856 100644 --- a/src/VisualStudio/Core/Test/project.json +++ b/src/VisualStudio/Core/Test/project.json @@ -20,6 +20,10 @@ "version": "14.3.25407", "suppressParent": "all" }, + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal" : { + "version": "14.3.25407", + "suppressParent": "all" + }, "RoslynDependencies.Microsoft.Internal.VisualStudio.Shell.Interop.14.0.DesignTime": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/VisualStudio/InteractiveServices/VisualStudioInteractiveServices.csproj b/src/VisualStudio/InteractiveServices/VisualStudioInteractiveServices.csproj index ef3ffdcb927cc..3178806c9134e 100644 --- a/src/VisualStudio/InteractiveServices/VisualStudioInteractiveServices.csproj +++ b/src/VisualStudio/InteractiveServices/VisualStudioInteractiveServices.csproj @@ -59,10 +59,6 @@ {8E2A252E-A140-45A6-A81A-2652996EA589} InteractiveFeatures - - {01E9BD68-0339-4A13-B42F-A3CA84D164F3} - InteractiveWindow - {18F5FBB8-7570-4412-8CC7-0A86FF13B7BA} TextEditorFeatures @@ -75,10 +71,6 @@ {86FD5B9A-4FA0-4B10-B59F-CFAF077A859C} ServicesVisualStudio - - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} - VisualStudioInteractiveWindow - diff --git a/src/VisualStudio/InteractiveServices/project.json b/src/VisualStudio/InteractiveServices/project.json index 9508be3b00aa6..5c71ea5395d06 100644 --- a/src/VisualStudio/InteractiveServices/project.json +++ b/src/VisualStudio/InteractiveServices/project.json @@ -2,7 +2,8 @@ "dependencies": { "RoslynDependencies.Microsoft.VisualStudio.ComponentModelHost": "14.3.25407", "Microsoft.VisualStudio.Editor": "14.3.25407", - "Microsoft.VisualStudio.Shell.14.0": "14.3.25407" + "Microsoft.VisualStudio.Shell.14.0": "14.3.25407", + "Microsoft.VisualStudio.VsInteractiveWindow": "2.0.0-beta5-60820-04" }, "frameworks": { "net46": { } diff --git a/src/VisualStudio/SetupInteractive/VisualStudioSetupInteractive.csproj b/src/VisualStudio/SetupInteractive/VisualStudioSetupInteractive.csproj index 6621a83d76ad6..d23af898b24d3 100644 --- a/src/VisualStudio/SetupInteractive/VisualStudioSetupInteractive.csproj +++ b/src/VisualStudio/SetupInteractive/VisualStudioSetupInteractive.csproj @@ -25,16 +25,6 @@ v4.6 - - {20bb6fac-44d2-4d76-abfe-0c1e163a1a4f} - VisualStudioInteractiveWindow - false - False - - - - - {737ff62c-f068-4317-84d0-bfb210c17a4e} CSharpVisualStudioRepl @@ -105,4 +95,4 @@ - + \ No newline at end of file diff --git a/src/VisualStudio/SetupInteractive/source.extension.vsixmanifest b/src/VisualStudio/SetupInteractive/source.extension.vsixmanifest index 8adcaaa77e3fb..3421b61088f63 100644 --- a/src/VisualStudio/SetupInteractive/source.extension.vsixmanifest +++ b/src/VisualStudio/SetupInteractive/source.extension.vsixmanifest @@ -22,7 +22,6 @@ - diff --git a/src/VisualStudio/TestUtilities/VisualStudioTestUtilities.csproj b/src/VisualStudio/TestUtilities/VisualStudioTestUtilities.csproj index 3ab61ff86432d..efd27d42587f8 100644 --- a/src/VisualStudio/TestUtilities/VisualStudioTestUtilities.csproj +++ b/src/VisualStudio/TestUtilities/VisualStudioTestUtilities.csproj @@ -100,14 +100,6 @@ {edc68a0e-c68d-4a74-91b7-bf38ec909888} Features - - {01e9bd68-0339-4a13-b42f-a3ca84d164f3} - InteractiveWindow - - - {20bb6fac-44d2-4d76-abfe-0c1e163a1a4f} - VisualStudioInteractiveWindow - {e2e889a5-2489-4546-9194-47c63e49eaeb} Diagnostics diff --git a/src/VisualStudio/TestUtilities/project.json b/src/VisualStudio/TestUtilities/project.json index 4a597159cb5b1..303c4aa3ce5d5 100644 --- a/src/VisualStudio/TestUtilities/project.json +++ b/src/VisualStudio/TestUtilities/project.json @@ -1,5 +1,9 @@ { "dependencies": { + "RoslynDependencies.Microsoft.VisualStudio.Text.Internal" : { + "version": "14.3.25407", + "suppressParent": "all" + }, "Microsoft.VisualStudio.Language.Intellisense": { "version": "14.3.25407", "suppressParent": "all" diff --git a/src/VisualStudio/VisualBasic/Repl/BasicVisualStudioRepl.vbproj b/src/VisualStudio/VisualBasic/Repl/BasicVisualStudioRepl.vbproj index 55bc02b598eb2..1cb5e34d69173 100644 --- a/src/VisualStudio/VisualBasic/Repl/BasicVisualStudioRepl.vbproj +++ b/src/VisualStudio/VisualBasic/Repl/BasicVisualStudioRepl.vbproj @@ -24,14 +24,6 @@ {1ee8cad3-55f9-4d91-96b2-084641da9a6c} CodeAnalysis - - {01e9bd68-0339-4a13-b42f-a3ca84d164f3} - InteractiveWindow - - - {20bb6fac-44d2-4d76-abfe-0c1e163a1a4f} - VisualStudioInteractiveWindow - {5f8d2414-064a-4b3a-9b42-8e2a04246be5} Workspaces diff --git a/src/VisualStudio/VisualStudioInteractiveComponents/VisualStudioInteractiveComponents.csproj b/src/VisualStudio/VisualStudioInteractiveComponents/VisualStudioInteractiveComponents.csproj index 6ad626405e96f..f316549f32049 100644 --- a/src/VisualStudio/VisualStudioInteractiveComponents/VisualStudioInteractiveComponents.csproj +++ b/src/VisualStudio/VisualStudioInteractiveComponents/VisualStudioInteractiveComponents.csproj @@ -86,16 +86,6 @@ DebugSymbolsProjectOutputGroup true - - {20BB6FAC-44D2-4D76-ABFE-0C1E163A1A4F} - VisualStudioInteractiveWindow - false - False - - - - - {EDC68A0E-C68D-4A74-91B7-BF38EC909888} Features @@ -194,4 +184,4 @@ - + \ No newline at end of file diff --git a/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest b/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest index 435bb95f42af7..1a72b92a251a3 100644 --- a/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest +++ b/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest @@ -31,7 +31,6 @@ -