diff options
Diffstat (limited to 'main/src/addins')
426 files changed, 7008 insertions, 4932 deletions
diff --git a/main/src/addins/AspNet/Commands/AddControllerDialog.cs b/main/src/addins/AspNet/Commands/AddControllerDialog.cs index 603e60dbf0..c3af4ed5db 100644 --- a/main/src/addins/AspNet/Commands/AddControllerDialog.cs +++ b/main/src/addins/AspNet/Commands/AddControllerDialog.cs @@ -29,6 +29,7 @@ using System.Collections.Generic; using Gtk;
using MonoDevelop.Core;
using MonoDevelop.AspNet.Projects;
+using MonoDevelop.Projects;
namespace MonoDevelop.AspNet.Commands
{
@@ -57,13 +58,14 @@ namespace MonoDevelop.AspNet.Commands }
}
- public AddControllerDialog (AspNetAppProject project)
+ public AddControllerDialog (DotNetProject project)
{
Build ();
+ var ext = project.GetService<AspNetFlavor> ();
provider = project.LanguageBinding.GetCodeDomProvider ();
- loadedTemplateList = project.GetCodeTemplates ("AddController");
+ loadedTemplateList = ext.GetCodeTemplates ("AddController");
bool foundEmptyTemplate = false;
int templateIndex = 0;
foreach (string file in loadedTemplateList) {
diff --git a/main/src/addins/AspNet/Commands/AddViewDialog.cs b/main/src/addins/AspNet/Commands/AddViewDialog.cs index c9d4c56a21..ef54af54bb 100644 --- a/main/src/addins/AspNet/Commands/AddViewDialog.cs +++ b/main/src/addins/AspNet/Commands/AddViewDialog.cs @@ -37,12 +37,14 @@ using MonoDevelop.AspNet.Projects; using MonoDevelop.AspNet.WebForms.Dom; using MonoDevelop.AspNet.WebForms; using Gtk; +using MonoDevelop.Projects; namespace MonoDevelop.AspNet.Commands { class AddViewDialog : Dialog { - readonly AspNetAppProject project;
+ readonly DotNetProject project; + readonly AspNetFlavor aspFlavor;
IDictionary<string, IList<string>> loadedTemplateList;
IDictionary<string, ListStore> templateStore;
ListStore dataClassStore;
@@ -61,9 +63,10 @@ namespace MonoDevelop.AspNet.Commands CheckButton partialCheck, stronglyTypedCheck, masterCheck; Alignment typePanel, masterPanel; - public AddViewDialog (AspNetAppProject project) + public AddViewDialog (DotNetProject project) { this.project = project; + aspFlavor = project.GetService<AspNetFlavor> (); Build (); @@ -73,14 +76,14 @@ namespace MonoDevelop.AspNet.Commands loadedTemplateList = new Dictionary<string, IList<string>> ();
foreach (var engine in viewEngines) {
viewEngineCombo.AppendText (engine);
- loadedTemplateList[engine] = project.GetCodeTemplates ("AddView", engine);
+ loadedTemplateList[engine] = aspFlavor.GetCodeTemplates ("AddView", engine);
}
viewEngineCombo.Active = 0;
InitializeTemplateStore (loadedTemplateList); ContentPlaceHolders = new List<string> (); - string siteMaster = project.VirtualToLocalPath ("~/Views/Shared/Site.master", null); + string siteMaster = aspFlavor.VirtualToLocalPath ("~/Views/Shared/Site.master", null); if (project.Files.GetFile (siteMaster) != null) masterEntry.Text = "~/Views/Shared/Site.master"; @@ -221,7 +224,7 @@ namespace MonoDevelop.AspNet.Commands IEnumerable<string> GetProperViewEngines ()
{
yield return "Aspx";
- if (project.SupportsRazorViewEngine)
+ if (aspFlavor.SupportsRazorViewEngine)
yield return "Razor";
}
@@ -307,7 +310,7 @@ namespace MonoDevelop.AspNet.Commands return false;
if (!IsPartialView && HasMaster && ActiveViewEngine != "Razor") {
- if (String.IsNullOrEmpty (MasterFile) || !File.Exists (project.VirtualToLocalPath (oldMaster, null)))
+ if (String.IsNullOrEmpty (MasterFile) || !File.Exists (aspFlavor.VirtualToLocalPath (oldMaster, null)))
return false;
//PrimaryPlaceHolder can be empty
//Layout Page can be empty in Razor Views - it's usually set in _ViewStart.cshtml file
@@ -341,7 +344,7 @@ namespace MonoDevelop.AspNet.Commands }; try { if (MessageService.RunCustomDialog (dialog) == (int) ResponseType.Ok) - masterEntry.Text = project.LocalToVirtualPath (dialog.SelectedFile.FilePath); + masterEntry.Text = aspFlavor.LocalToVirtualPath (dialog.SelectedFile.FilePath); } finally { dialog.Destroy (); } @@ -359,7 +362,7 @@ namespace MonoDevelop.AspNet.Commands primaryPlaceholderStore.Clear (); ContentPlaceHolders.Clear (); - string realPath = project.VirtualToLocalPath (oldMaster, null); + string realPath = aspFlavor.VirtualToLocalPath (oldMaster, null); if (!File.Exists (realPath)) return; diff --git a/main/src/addins/AspNet/Commands/AddViewFromControllerCommandHandler.cs b/main/src/addins/AspNet/Commands/AddViewFromControllerCommandHandler.cs index 0bf46856ec..0d732c6f54 100644 --- a/main/src/addins/AspNet/Commands/AddViewFromControllerCommandHandler.cs +++ b/main/src/addins/AspNet/Commands/AddViewFromControllerCommandHandler.cs @@ -28,6 +28,7 @@ using System; using MonoDevelop.Components.Commands;
using MonoDevelop.Ide;
using MonoDevelop.AspNet.Projects;
+using MonoDevelop.Projects;
namespace MonoDevelop.AspNet.Commands
{
@@ -41,7 +42,7 @@ namespace MonoDevelop.AspNet.Commands protected override void Run ()
{
var doc = IdeApp.Workbench.ActiveDocument;
- var project = (AspNetAppProject)doc.Project;
+ var project = (DotNetProject)doc.Project;
var currentLocation = doc.Editor.Caret.Location;
string controllerName = doc.ParsedDocument.GetTopLevelTypeDefinition (currentLocation).Name;
@@ -54,7 +55,7 @@ namespace MonoDevelop.AspNet.Commands AddView (project, path, actionName);
}
- public static void AddView (AspNetAppProject project, string path, string name)
+ public static void AddView (DotNetProject project, string path, string name)
{
var provider = project.LanguageBinding.GetCodeDomProvider ();
if (provider == null)
@@ -125,7 +126,7 @@ namespace MonoDevelop.AspNet.Commands if (System.IO.File.Exists (outputFile)) {
project.AddFile (outputFile);
- IdeApp.ProjectOperations.Save (project);
+ IdeApp.ProjectOperations.SaveAsync (project);
}
}
}
diff --git a/main/src/addins/AspNet/Commands/GoToControllerCommandHandler.cs b/main/src/addins/AspNet/Commands/GoToControllerCommandHandler.cs index ed2251cb31..3e62a685bb 100644 --- a/main/src/addins/AspNet/Commands/GoToControllerCommandHandler.cs +++ b/main/src/addins/AspNet/Commands/GoToControllerCommandHandler.cs @@ -40,8 +40,12 @@ namespace MonoDevelop.AspNet.Commands protected override void Update (CommandInfo info)
{
var doc = IdeApp.Workbench.ActiveDocument;
- AspNetAppProject project;
- if (doc == null || (project = doc.Project as AspNetAppProject) == null || !project.IsAspMvcProject) {
+ if (doc == null || doc.Project == null) {
+ info.Enabled = info.Visible = false;
+ return;
+ }
+ var aspFlavor = doc.Project.GetService<AspNetFlavor> ();
+ if (aspFlavor == null || !aspFlavor.IsAspMvcProject) {
info.Enabled = info.Visible = false;
return;
}
diff --git a/main/src/addins/AspNet/Commands/MvcCommandsCommonHandler.cs b/main/src/addins/AspNet/Commands/MvcCommandsCommonHandler.cs index 03fa16fb63..fcc9aa7acd 100644 --- a/main/src/addins/AspNet/Commands/MvcCommandsCommonHandler.cs +++ b/main/src/addins/AspNet/Commands/MvcCommandsCommonHandler.cs @@ -38,8 +38,12 @@ namespace MonoDevelop.AspNet.Commands public static void Update (CommandInfo info)
{
var doc = IdeApp.Workbench.ActiveDocument;
- AspNetAppProject project;
- if (doc == null || (project = doc.Project as AspNetAppProject) == null || !project.IsAspMvcProject || doc.ParsedDocument == null) {
+ if (doc == null || doc.Project == null || doc.ParsedDocument == null) {
+ info.Enabled = info.Visible = false;
+ return;
+ }
+ var aspFlavor = doc.Project.GetService<AspNetFlavor> ();
+ if (aspFlavor == null || !aspFlavor.IsAspMvcProject) {
info.Enabled = info.Visible = false;
return;
}
diff --git a/main/src/addins/AspNet/Execution/AspNetExecutionHandler.cs b/main/src/addins/AspNet/Execution/AspNetExecutionHandler.cs index 2e0dcca894..19566f4656 100644 --- a/main/src/addins/AspNet/Execution/AspNetExecutionHandler.cs +++ b/main/src/addins/AspNet/Execution/AspNetExecutionHandler.cs @@ -89,7 +89,7 @@ namespace MonoDevelop.AspNet.Execution return cmd != null && !string.IsNullOrEmpty (GetXspName (cmd)); } - public IProcessAsyncOperation Execute (ExecutionCommand command, IConsole console) + public ProcessAsyncOperation Execute (ExecutionCommand command, IConsole console) { var cmd = (AspNetExecutionCommand) command; var xspPath = GetXspPath (cmd); diff --git a/main/src/addins/AspNet/Execution/BrowserLauncher.cs b/main/src/addins/AspNet/Execution/BrowserLauncher.cs index 6a03216721..628b4cdd00 100644 --- a/main/src/addins/AspNet/Execution/BrowserLauncher.cs +++ b/main/src/addins/AspNet/Execution/BrowserLauncher.cs @@ -35,7 +35,7 @@ namespace MonoDevelop.AspNet.Execution { static class BrowserLauncher { - public static IProcessAsyncOperation LaunchDefaultBrowser (string url) + public static ProcessAsyncOperation LaunchDefaultBrowser (string url) { try { DesktopService.ShowUrl (url); diff --git a/main/src/addins/AspNet/Execution/XspOptionsPanel.cs b/main/src/addins/AspNet/Execution/XspOptionsPanel.cs index 6bd97b965d..1565afca86 100644 --- a/main/src/addins/AspNet/Execution/XspOptionsPanel.cs +++ b/main/src/addins/AspNet/Execution/XspOptionsPanel.cs @@ -41,12 +41,12 @@ namespace MonoDevelop.AspNet.Execution public override Widget CreatePanelWidget () { - return panel = new XspOptionsPanelWidget ((AspNetAppProject) ConfiguredProject); + return panel = new XspOptionsPanelWidget (ConfiguredProject.GetService<AspNetFlavor> ()); } public override void ApplyChanges () { - panel.Store ((AspNetAppProject) ConfiguredProject); + panel.Store (ConfiguredProject.GetService<AspNetFlavor> ()); } } } diff --git a/main/src/addins/AspNet/Execution/XspOptionsPanelWidget.cs b/main/src/addins/AspNet/Execution/XspOptionsPanelWidget.cs index 18126f4836..da3a559f14 100644 --- a/main/src/addins/AspNet/Execution/XspOptionsPanelWidget.cs +++ b/main/src/addins/AspNet/Execution/XspOptionsPanelWidget.cs @@ -46,7 +46,7 @@ namespace MonoDevelop.AspNet.Execution readonly FileEntry certLocation = new FileEntry (); readonly Entry passwordEntry = new Entry { InvisibleChar = '●' }; - public XspOptionsPanelWidget (AspNetAppProject project) + public XspOptionsPanelWidget (AspNetFlavor project) { Build (); @@ -165,7 +165,7 @@ namespace MonoDevelop.AspNet.Execution ShowAll (); } - public void Store (AspNetAppProject project) + public void Store (AspNetFlavor project) { XspParameters xPar = project.XspParameters; diff --git a/main/src/addins/AspNet/Makefile.am b/main/src/addins/AspNet/Makefile.am index b8a06787c8..2dc30cad76 100644 --- a/main/src/addins/AspNet/Makefile.am +++ b/main/src/addins/AspNet/Makefile.am @@ -1,4 +1,4 @@ include $(top_srcdir)/xbuild.include EXTRA_DIST += \ $(wildcard lib/*) \ - $(wildcard Templates/Common/*.cshtml) + $(wildcard Templates/MvcCommon/*.cshtml) diff --git a/main/src/addins/AspNet/MonoDevelop.AspNet.csproj b/main/src/addins/AspNet/MonoDevelop.AspNet.csproj index 26e3e80662..f0b66a4ae4 100644 --- a/main/src/addins/AspNet/MonoDevelop.AspNet.csproj +++ b/main/src/addins/AspNet/MonoDevelop.AspNet.csproj @@ -9,6 +9,7 @@ <OutputType>Library</OutputType> <AssemblyName>MonoDevelop.AspNet</AssemblyName> <RootNamespace>MonoDevelop.AspNet</RootNamespace> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>True</DebugSymbols> @@ -125,6 +126,7 @@ <Reference Include="System.Web.WebPages.Razor"> <HintPath>..\..\..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath> </Reference> + <Reference Condition="!Exists('$(SolutionDir)\..\.git')" Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <Reference Include="System.Web.Mvc"> <HintPath>..\..\..\packages\Microsoft.AspNet.Mvc.4.0.30506.0\lib\net40\System.Web.Mvc.dll</HintPath> </Reference> @@ -187,8 +189,6 @@ <Compile Include="Razor\EditorParserFixed\RazorResources.Designer.cs" /> <Compile Include="Projects\AspMvcProject.cs" /> <Compile Include="Projects\AspMvcProjectConfiguration.cs" /> - <Compile Include="Projects\AspNetAppProject.cs" /> - <Compile Include="Projects\AspNetAppProjectBinding.cs" /> <Compile Include="Projects\AspNetAppProjectConfiguration.cs" /> <Compile Include="Projects\AspNetMSBuildImportProvider.cs" /> <Compile Include="WebForms\MasterContentFileDescriptionTemplate.cs" /> @@ -290,6 +290,7 @@ <Compile Include="Razor\RazorCSharpParsedDocument.cs" /> <Compile Include="Razor\RazorPageInfo.cs" /> <Compile Include="WebForms\WebFormsTypeContext.cs" /> + <Compile Include="Projects\AspNetFlavor.cs" /> </ItemGroup> <ItemGroup> <None Include="Makefile.am" /> @@ -490,10 +491,9 @@ </ItemGroup> <Target Name="BeforeBuild"> <PropertyGroup> - <NuGet>..\..\..\external\nuget-binary\NuGet.exe</NuGet> + <NuGet>$(SolutionDir)\external\nuget-binary\NuGet.exe</NuGet> <NuGet Condition="$(OS)=='Unix'">mono $(NuGet)</NuGet> - <SlnDir>..\..\..</SlnDir> </PropertyGroup> - <Exec Command="$(NuGet) restore -SolutionDirectory $(SlnDir)" /> + <Exec Condition="Exists('$(SolutionDir)\..\.git')" Command="$(NuGet) restore -SolutionDirectory $(SolutionDir)" /> </Target> </Project> diff --git a/main/src/addins/AspNet/ProjectPad/AspNetFolderNodeCommandHandler.cs b/main/src/addins/AspNet/ProjectPad/AspNetFolderNodeCommandHandler.cs index 30e870fccc..b6f5169fc6 100644 --- a/main/src/addins/AspNet/ProjectPad/AspNetFolderNodeCommandHandler.cs +++ b/main/src/addins/AspNet/ProjectPad/AspNetFolderNodeCommandHandler.cs @@ -31,7 +31,8 @@ using MonoDevelop.Ide.Gui.Components; using MonoDevelop.Ide.Gui.Pads.ProjectPad; using MonoDevelop.Ide; using MonoDevelop.AspNet.Projects;
-using MonoDevelop.AspNet.Commands; +using MonoDevelop.AspNet.Commands;
+using MonoDevelop.Projects; namespace MonoDevelop.AspNet.ProjectPad { @@ -40,8 +41,9 @@ namespace MonoDevelop.AspNet.ProjectPad [CommandUpdateHandler (AspNetCommands.AddController)] public void AddControllerUpdate (CommandInfo info) { - var project = CurrentNode.GetParentDataItem (typeof (AspNetAppProject), true) as AspNetAppProject; - if (project == null || !project.IsAspMvcProject) { + var project = CurrentNode.GetParentDataItem (typeof (DotNetProject), true) as DotNetProject;
+ var aspFlavor = project != null ? project.GetService<AspNetFlavor> () : null; + if (aspFlavor == null || !aspFlavor.IsAspMvcProject) { info.Enabled = info.Visible = false; return; } @@ -54,7 +56,7 @@ namespace MonoDevelop.AspNet.ProjectPad [CommandHandler (AspNetCommands.AddController)] public void AddController () { - var project = (AspNetAppProject) CurrentNode.GetParentDataItem (typeof (AspNetAppProject), true); + var project = (DotNetProject) CurrentNode.GetParentDataItem (typeof (DotNetProject), true); object currentItem = CurrentNode.DataItem;
@@ -68,7 +70,7 @@ namespace MonoDevelop.AspNet.ProjectPad nav.Expanded = true; } - public static void AddController (AspNetAppProject project, string path, string name) + public static void AddController (DotNetProject project, string path, string name) {
var provider = project.LanguageBinding.GetCodeDomProvider ();
if (provider == null)
@@ -119,15 +121,15 @@ namespace MonoDevelop.AspNet.ProjectPad if (System.IO.File.Exists (outputFile)) {
project.AddFile (outputFile);
- IdeApp.ProjectOperations.Save (project);
+ IdeApp.ProjectOperations.SaveAsync (project);
} } [CommandUpdateHandler (AspNetCommands.AddView)] public void AddViewUpdate (CommandInfo info) { - var project = CurrentNode.GetParentDataItem (typeof (AspNetAppProject), true) as AspNetAppProject; - if (project == null || !project.IsAspMvcProject) { + var project = CurrentNode.GetParentDataItem<DotNetProject> (true); + if (project == null || !project.HasFlavor<AspNetFlavor>() || !project.GetFlavor<AspNetFlavor>().IsAspMvcProject) { info.Enabled = info.Visible = false; return; } @@ -140,7 +142,7 @@ namespace MonoDevelop.AspNet.ProjectPad [CommandHandler (AspNetCommands.AddView)] public void AddView () { - var project = (AspNetAppProject) CurrentNode.GetParentDataItem (typeof (AspNetAppProject), true); + var project = CurrentNode.GetParentDataItem<DotNetProject> (true); object currentItem = CurrentNode.DataItem; diff --git a/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeBuilderExtension.cs b/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeBuilderExtension.cs index da125b8376..572f5e864b 100644 --- a/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeBuilderExtension.cs +++ b/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeBuilderExtension.cs @@ -29,6 +29,7 @@ using System; using MonoDevelop.Ide.Gui.Components; using MonoDevelop.AspNet.Projects; +using MonoDevelop.Projects; namespace MonoDevelop.AspNet.ProjectPad { @@ -36,7 +37,7 @@ namespace MonoDevelop.AspNet.ProjectPad { public override bool CanBuildNode (Type dataType) { - return typeof(AspNetAppProject).IsAssignableFrom (dataType); + return typeof(DotNetProject).IsAssignableFrom (dataType); } public override Type CommandHandlerType { diff --git a/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeCommandHandler.cs b/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeCommandHandler.cs index 3bf027f7c8..3373c62b1b 100644 --- a/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeCommandHandler.cs +++ b/main/src/addins/AspNet/ProjectPad/AspNetProjectNodeCommandHandler.cs @@ -42,21 +42,25 @@ namespace MonoDevelop.AspNet.ProjectPad [CommandHandler (AspNetCommands.AddAspNetDirectory)] public void OnAddSpecialDirectory (object ob) { - AspNetAppProject proj = CurrentNode.DataItem as AspNetAppProject; + var proj = CurrentNode.DataItem as DotNetProject; if (proj == null) return; proj.AddDirectory ((string) ob); - IdeApp.ProjectOperations.Save (proj); + IdeApp.ProjectOperations.SaveAsync (proj); } [CommandUpdateHandler (AspNetCommands.AddAspNetDirectory)] public void OnAddSpecialDirectoryUpdate (CommandArrayInfo info) { - AspNetAppProject proj = CurrentNode.DataItem as AspNetAppProject; - if (proj == null) - return; - - List<string> dirs = new List<string> (proj.GetSpecialDirectories ()); + var proj = CurrentNode.DataItem as DotNetProject; + if (proj == null)
+ return;
+
+ var asp = proj.GetFlavor<AspNetFlavor> ();
+ if (asp == null)
+ return;
+ + List<string> dirs = new List<string> (asp.GetSpecialDirectories ()); dirs.Sort ();
List<FilePath> fullPaths = new List<FilePath> (dirs.Count); foreach (string s in dirs) diff --git a/main/src/addins/AspNet/Projects/AspMvcProject.cs b/main/src/addins/AspNet/Projects/AspMvcProject.cs index 8161c25ee2..9faf060a04 100644 --- a/main/src/addins/AspNet/Projects/AspMvcProject.cs +++ b/main/src/addins/AspNet/Projects/AspMvcProject.cs @@ -31,37 +31,21 @@ using MonoDevelop.Projects; namespace MonoDevelop.AspNet.Projects { - abstract class AspMvcProject : AspNetAppProject + abstract class AspMvcProject : AspNetFlavor { - protected AspMvcProject () - { - } - - protected AspMvcProject (string languageName) - : base (languageName) - { - } - - protected AspMvcProject (string languageName, ProjectCreateInformation info, XmlElement projectOptions) - : base (languageName, info, projectOptions) - { - } - - public override SolutionItemConfiguration CreateConfiguration (string name) + protected override SolutionItemConfiguration OnCreateConfiguration (string name) { var conf = new AspMvcProjectConfiguration (name); - conf.CopyFrom (base.CreateConfiguration (name)); + conf.CopyFrom (base.OnCreateConfiguration (name)); return conf; } - public override IEnumerable<string> GetProjectTypes () + protected override void OnGetProjectTypes (HashSet<string> types) { - yield return "AspNetMvc"; - foreach (var t in base.GetProjectTypes ()) - yield return t; + types.Add ("AspNetMvc"); } - public override bool SupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework) + protected override bool OnGetSupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework) { return framework.CanReferenceAssembliesTargetingFramework (MonoDevelop.Core.Assemblies.TargetFrameworkMoniker.NET_3_5); } @@ -75,20 +59,6 @@ namespace MonoDevelop.AspNet.Projects class AspMvc1Project : AspMvcProject
{
- public AspMvc1Project ()
- {
- }
-
- public AspMvc1Project (string languageName)
- : base (languageName)
- {
- }
-
- public AspMvc1Project (string languageName, ProjectCreateInformation info, XmlElement projectOptions)
- : base (languageName, info, projectOptions)
- {
- } - protected override string GetDefaultAspNetMvcVersion () { return "1.0.0.0"; @@ -97,20 +67,6 @@ namespace MonoDevelop.AspNet.Projects class AspMvc2Project : AspMvcProject
{
- public AspMvc2Project ()
- {
- }
-
- public AspMvc2Project (string languageName)
- : base (languageName)
- {
- }
-
- public AspMvc2Project (string languageName, ProjectCreateInformation info, XmlElement projectOptions)
- : base (languageName, info, projectOptions)
- {
- } - protected override string GetDefaultAspNetMvcVersion () { return "2.0.0.0"; @@ -119,21 +75,7 @@ namespace MonoDevelop.AspNet.Projects class AspMvc3Project : AspMvcProject
{
- public AspMvc3Project ()
- {
- }
-
- public AspMvc3Project (string languageName)
- : base (languageName)
- {
- }
-
- public AspMvc3Project (string languageName, ProjectCreateInformation info, XmlElement projectOptions)
- : base (languageName, info, projectOptions)
- {
- }
-
- public override bool SupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework)
+ protected override bool OnGetSupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework)
{
return framework.CanReferenceAssembliesTargetingFramework (MonoDevelop.Core.Assemblies.TargetFrameworkMoniker.NET_4_0);
} @@ -146,21 +88,7 @@ namespace MonoDevelop.AspNet.Projects class AspMvc4Project : AspMvcProject { - public AspMvc4Project () - { - } - - public AspMvc4Project (string languageName) - : base (languageName) - { - } - - public AspMvc4Project (string languageName, ProjectCreateInformation info, XmlElement projectOptions) - : base (languageName, info, projectOptions) - { - } - - public override bool SupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework) + protected override bool OnGetSupportsFramework (MonoDevelop.Core.Assemblies.TargetFramework framework) { return framework.CanReferenceAssembliesTargetingFramework (MonoDevelop.Core.Assemblies.TargetFrameworkMoniker.NET_4_0); } diff --git a/main/src/addins/AspNet/Projects/AspNetAppProjectBinding.cs b/main/src/addins/AspNet/Projects/AspNetAppProjectBinding.cs deleted file mode 100644 index 3a89feac81..0000000000 --- a/main/src/addins/AspNet/Projects/AspNetAppProjectBinding.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// AspNetAppProjectBinding.cs: Project binding for AspNetAppProject -// -// Authors: -// Michael Hutchinson <m.j.hutchinson@gmail.com> -// -// Copyright (C) 2006 Michael Hutchinson -// -// -// This source code is licenced under The MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.IO; -using MonoDevelop.Core; -using MonoDevelop.Projects; -using MonoDevelop.Core.Serialization; -using System.Xml; - -namespace MonoDevelop.AspNet.Projects -{ - //based heavily on DotNetProjectBinding - public class AspNetAppProjectBinding : IProjectBinding - { - - public string Name { - get { return "AspNetApp"; } - } - - public Project CreateProject (ProjectCreateInformation info, XmlElement projectOptions) - { - string lang = projectOptions.GetAttribute ("language"); - return CreateProject (lang, info, projectOptions); - } - - public Project CreateProject (string language, ProjectCreateInformation info, XmlElement projectOptions) - { - return new AspNetAppProject (language, info, projectOptions); - } - - public Project CreateSingleFileProject (string file) - { - //TODO: get page language - string language = "C#"; - - var info = new ProjectCreateInformation () { - ProjectName = Path.GetFileNameWithoutExtension (file), - SolutionPath = Path.GetDirectoryName (file), - ProjectBasePath = Path.GetDirectoryName (file), - }; - var project = CreateProject (language, info, null); - project.Files.Add (new ProjectFile (file)); - return project; - } - - public bool CanCreateSingleFileProject (string sourceFile) - { - WebSubtype type = AspNetAppProject.DetermineWebSubtype (sourceFile); - - return ((type == WebSubtype.WebForm) - || (type == WebSubtype.WebHandler) - || (type == WebSubtype.WebService)); - } - } -} diff --git a/main/src/addins/AspNet/Projects/AspNetAppProject.cs b/main/src/addins/AspNet/Projects/AspNetFlavor.cs index ef44893202..96902a8fdb 100644 --- a/main/src/addins/AspNet/Projects/AspNetAppProject.cs +++ b/main/src/addins/AspNet/Projects/AspNetFlavor.cs @@ -16,10 +16,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -49,148 +49,130 @@ using MonoDevelop.Ide.TypeSystem; using MonoDevelop.Projects; using MonoDevelop.AspNet.Execution; using MonoDevelop.AspNet.WebForms; +using System.Threading.Tasks; namespace MonoDevelop.AspNet.Projects { [DataInclude (typeof(AspNetAppProjectConfiguration))] - public class AspNetAppProject : DotNetAssemblyProject + public class AspNetFlavor : DotNetProjectExtension { [ItemProperty("XspParameters", IsExternal=true)] XspParameters xspParameters = new XspParameters (); WebFormsRegistrationCache registrationCache; WebFormsCodeBehindTypeNameCache codebehindTypeNameCache; - + #region properties - public override IEnumerable<string> GetProjectTypes () + protected override void OnGetProjectTypes (HashSet<string> types) { - yield return "AspNetApp"; - foreach (var t in base.GetProjectTypes ()) - yield return t; + types.Add ("AspNetApp"); } - public override bool IsLibraryBasedProjectType { + protected override bool IsLibraryBasedProjectType { get { return true; } } - + public XspParameters XspParameters { get { return xspParameters; } } - + internal WebFormsRegistrationCache RegistrationCache { get { if (registrationCache == null) - registrationCache = new WebFormsRegistrationCache (this); + registrationCache = new WebFormsRegistrationCache (Project); return registrationCache; } } - + #endregion - + #region constructors - - public AspNetAppProject () - { - Init (); - } - - public AspNetAppProject (string languageName) - : base (languageName) - { - Init (); - } - - public AspNetAppProject (string languageName, ProjectCreateInformation info, XmlElement projectOptions) - : base (languageName, info, projectOptions) + + protected override void OnInitializeNew (string languageName, ProjectCreateInformation info, XmlElement projectOptions) { - Init (); - + base.OnInitializeNew (languageName, info, projectOptions); + codebehindTypeNameCache = new WebFormsCodeBehindTypeNameCache (Project); + var binPath = info == null? (FilePath)"bin" : info.BinPath; - foreach (var cfg in Configurations.Cast<AspNetAppProjectConfiguration> ()) + foreach (var cfg in Project.Configurations.Cast<DotNetProjectConfiguration> ()) cfg.OutputDirectory = binPath; - } - - public override SolutionItemConfiguration CreateConfiguration (string name) + } + + protected override SolutionItemConfiguration OnCreateConfiguration (string name) { var conf = new AspNetAppProjectConfiguration (name); - conf.CopyFrom (base.CreateConfiguration (name)); - conf.OutputDirectory = BaseDirectory.IsNullOrEmpty? "bin" : (string)BaseDirectory.Combine ("bin"); + conf.CopyFrom (base.OnCreateConfiguration (name)); + conf.OutputDirectory = Project.BaseDirectory.IsNullOrEmpty? "bin" : (string)Project.BaseDirectory.Combine ("bin"); return conf; } - - void Init () - { - codebehindTypeNameCache = new WebFormsCodeBehindTypeNameCache (this); - } - public new AspNetAppProjectConfiguration GetConfiguration (ConfigurationSelector configuration) + public AspNetAppProjectConfiguration GetConfiguration (ConfigurationSelector configuration) { - return (AspNetAppProjectConfiguration) base.GetConfiguration (configuration); + return (AspNetAppProjectConfiguration) Project.GetConfiguration (configuration); } - + #endregion - + public override void Dispose () { codebehindTypeNameCache.Dispose (); RegistrationCache.Dispose (); base.Dispose (); } - + #region build/prebuild/execute - - - protected override BuildResult DoBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + + + protected override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { //if no files are set to compile, then some compilers will error out //though this is valid with ASP.NET apps, so we just avoid calling the compiler in this case bool needsCompile = false; - foreach (ProjectFile pf in Files) { + foreach (ProjectFile pf in Project.Files) { if (pf.BuildAction == BuildAction.Compile) { needsCompile = true; break; } } - + if (needsCompile) - return base.DoBuild (monitor, configuration); - return new BuildResult (); + return base.OnBuild (monitor, configuration); + return Task.FromResult (BuildResult.Success); } - + ExecutionCommand CreateExecutionCommand (ConfigurationSelector config, AspNetAppProjectConfiguration configuration) { return new AspNetExecutionCommand { ClrVersion = configuration.ClrVersion, DebugMode = configuration.DebugMode, XspParameters = XspParameters, - BaseDirectory = BaseDirectory, - TargetRuntime = TargetRuntime, - TargetFramework = TargetFramework, - UserAssemblyPaths = GetUserAssemblyPaths (config), + BaseDirectory = Project.BaseDirectory, + TargetRuntime = Project.TargetRuntime, + TargetFramework = Project.TargetFramework, + UserAssemblyPaths = Project.GetUserAssemblyPaths (config), EnvironmentVariables = configuration.EnvironmentVariables, }; } - + protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) { var cmd = CreateExecutionCommand (configuration, GetConfiguration (configuration)); return context.ExecutionHandler.CanExecute (cmd); } - - protected override void DoExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + + protected async override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { //check XSP is available - + var cfg = GetConfiguration (configuration); var cmd = CreateExecutionCommand (configuration, cfg); var browserExcTarget = (BrowserExecutionTarget) context.ExecutionTarget; IConsole console = null; - var operationMonitor = new AggregatedOperationMonitor (monitor); bool isXsp = true; //FIXME: fix this when it might not be true - should delegate to the ExecutionHandler - + try { //HACK: check XSP exists first, because error UX is cleaner w/o displaying a blank console pad. if (isXsp) { @@ -211,8 +193,8 @@ namespace MonoDevelop.AspNet.Projects // The running Port value is now captured in the XspBrowserLauncherConsole object string url = String.Format ("http://{0}", XspParameters.Address); - - + + if (isXsp) { console = new XspBrowserLauncherConsole (console, delegate (string port) { if (browserExcTarget != null) @@ -221,53 +203,52 @@ namespace MonoDevelop.AspNet.Projects BrowserLauncher.LaunchDefaultBrowser (String.Format("{0}:{1}", url, port)); }); } - + monitor.Log.WriteLine ("Running web server..."); - + var op = context.ExecutionHandler.Execute (cmd, console); - operationMonitor.AddOperation (op); //handles cancellation - + if (!isXsp) { if (browserExcTarget != null) browserExcTarget.DesktopApp.Launch (url); else BrowserLauncher.LaunchDefaultBrowser (url); } - - op.WaitForCompleted (); - + + using (monitor.CancellationToken.Register (op.Cancel)) + await op.Task; + monitor.Log.WriteLine ("The web server exited with code: {0}", op.ExitCode); - + } catch (Exception ex) { if (!(ex is UserException)) { LoggingService.LogError ("Could not launch ASP.NET web server.", ex); } monitor.ReportError ("Could not launch web server.", ex); } finally { - operationMonitor.Dispose (); if (console != null) console.Dispose (); } } - + #endregion - + #region File utility methods - + public WebSubtype DetermineWebSubtype (ProjectFile file) { - if (LanguageBinding != null && LanguageBinding.IsSourceCodeFile (file.FilePath)) + if (Project.LanguageBinding != null && Project.LanguageBinding.IsSourceCodeFile (file.FilePath)) return WebSubtype.Code; return DetermineWebSubtype (file.Name); } - + public static WebSubtype DetermineWebSubtype (string fileName) { string extension = Path.GetExtension (fileName); if (extension == null) return WebSubtype.None; extension = extension.ToUpperInvariant ().TrimStart ('.'); - + //NOTE: No way to identify WebSubtype.Code from here //use the instance method for that switch (extension) { @@ -325,21 +306,21 @@ namespace MonoDevelop.AspNet.Projects return WebSubtype.None; } } - + #endregion - + #region special files - + #endregion - + public ProjectFile ResolveVirtualPath (string virtualPath, string relativeToFile) { string name = VirtualToLocalPath (virtualPath, relativeToFile); if (name == null) return null; - return Files.GetFile (name); + return Project.Files.GetFile (name); } - + public string VirtualToLocalPath (string virtualPath, string relativeToFile) { if (string.IsNullOrEmpty (virtualPath) || virtualPath [0] == '/' || virtualPath.IndexOf (':') > -1) @@ -351,60 +332,60 @@ namespace MonoDevelop.AspNet.Projects virtualPath = virtualPath.Substring (2); else virtualPath = virtualPath.Substring (1); - relativeToDir = BaseDirectory; + relativeToDir = Project.BaseDirectory; } else { relativeToDir = String.IsNullOrEmpty (relativeToFile) - ? BaseDirectory + ? Project.BaseDirectory : (FilePath) Path.GetDirectoryName (relativeToFile); } - + virtualPath = virtualPath.Replace ('/', Path.DirectorySeparatorChar); return relativeToDir.Combine (virtualPath).FullPath; } - + public string LocalToVirtualPath (string filename) { - string rel = FileService.AbsoluteToRelativePath (BaseDirectory, filename); + string rel = FileService.AbsoluteToRelativePath (Project.BaseDirectory, filename); return "~/" + rel.Replace (Path.DirectorySeparatorChar, '/'); } - + public string LocalToVirtualPath (ProjectFile file) { return LocalToVirtualPath (file.FilePath); } - + #region Reference handling - + protected override void OnReferenceAddedToProject (ProjectReferenceEventArgs e) { //short-circuit if the project is being deserialised - if (Loading) { + if (Project.Loading) { base.OnReferenceAddedToProject (e); return; } - + UpdateWebConfigRefs (); - + base.OnReferenceAddedToProject (e); } - + protected override void OnReferenceRemovedFromProject (ProjectReferenceEventArgs e) { //short-circuit if the project is being deserialised - if (Loading) { + if (Project.Loading) { base.OnReferenceAddedToProject (e); return; } - + UpdateWebConfigRefs (); - + base.OnReferenceRemovedFromProject (e); } - + void UpdateWebConfigRefs () { var refs = new List<string> (); - foreach (var reference in References) { + foreach (var reference in Project.References) { //local copied assemblies are copied to the bin directory so ASP.NET references them automatically if (reference.LocalCopy && (reference.ReferenceType == ReferenceType.Project || reference.ReferenceType == ReferenceType.Assembly)) continue; @@ -419,39 +400,39 @@ namespace MonoDevelop.AspNet.Projects continue; refs.Add (reference.Reference); } - + var webConfig = GetWebConfig (); if (webConfig == null || !File.Exists (webConfig.FilePath)) return; - + var textFile = TextFileProvider.Instance.GetEditableTextFile (webConfig.FilePath); //use textfile API because it's write safe (writes out to another file then moves) if (textFile == null) textFile = MonoDevelop.Projects.Text.TextFile.ReadFile (webConfig.FilePath); - + //can't use System.Web.Configuration.WebConfigurationManager, as it can only access virtual paths within an app //so need full manual handling try { var doc = new XmlDocument (); - + //FIXME: PreserveWhitespace doesn't handle whitespace in attribute lists //doc.PreserveWhitespace = true; doc.LoadXml (textFile.Text); - + //hunt our way to the assemblies element, creating elements if necessary XmlElement configElement = doc.DocumentElement; if (configElement == null || string.Compare (configElement.Name, "configuration", StringComparison.OrdinalIgnoreCase) != 0) { configElement = (XmlElement) doc.AppendChild (doc.CreateNode (XmlNodeType.Document, "configuration", null)); } - XmlElement webElement = GetNamedXmlElement (doc, configElement, "system.web"); + XmlElement webElement = GetNamedXmlElement (doc, configElement, "system.web"); XmlElement compilationNode = GetNamedXmlElement (doc, webElement, "compilation"); XmlElement assembliesNode = GetNamedXmlElement (doc, compilationNode, "assemblies"); - + List<XmlNode> existingAdds = new List<XmlNode> (); foreach (XmlNode node in assembliesNode) if (string.Compare (node.Name, "add", StringComparison.OrdinalIgnoreCase) == 0) existingAdds.Add (node); - + //add refs to the doc if they're not in it foreach (string reference in refs) { int index = 0; @@ -477,27 +458,27 @@ namespace MonoDevelop.AspNet.Projects assembliesNode.AppendChild (newAdd); } } - + //any nodes that weren't removed from the existingAdds list are old/redundant, so remove from doc foreach (XmlNode node in existingAdds) assembliesNode.RemoveChild (node); - + StringWriter sw = new StringWriter (); XmlTextWriter tw = new XmlTextWriter (sw); tw.Formatting = Formatting.Indented; doc.WriteTo (tw); tw.Flush (); textFile.Text = sw.ToString (); - + MonoDevelop.Projects.Text.TextFile tf = textFile as MonoDevelop.Projects.Text.TextFile; if (tf != null) tf.Save (); } catch (Exception e) { - LoggingService.LogWarning ("Could not modify application web.config in project " + Name, e); + LoggingService.LogWarning ("Could not modify application web.config in project " + Project.Name, e); } } - - + + XmlElement GetNamedXmlElement (XmlDocument doc, XmlElement parent, string name) { XmlElement result = null; @@ -513,78 +494,78 @@ namespace MonoDevelop.AspNet.Projects } return result; } - + ProjectFile GetWebConfig () { - var webConf = BaseDirectory.Combine ("web.config"); - foreach (var file in Files) + var webConf = Project.BaseDirectory.Combine ("web.config"); + foreach (var file in Project.Files) if (string.Compare (file.FilePath.ToString (), webConf, StringComparison.OrdinalIgnoreCase) == 0) return file; return null; } - + bool IsWebConfig (FilePath file) { - var webConf = BaseDirectory.Combine ("web.config"); + var webConf = Project.BaseDirectory.Combine ("web.config"); return (string.Compare (file, webConf, StringComparison.OrdinalIgnoreCase) == 0); } - + #endregion - + #region File event handlers - + protected override void OnFileAddedToProject (ProjectFileEventArgs e) { //short-circuit if the project is being deserialised - if (Loading) { + if (Project.Loading) { base.OnFileAddedToProject (e); return; } bool webConfigChange = false; List<string> filesToAdd = new List<string> (); - + foreach (ProjectFileEventInfo fargs in e) { IEnumerable<string> files = MonoDevelop.DesignerSupport.CodeBehind.GuessDependencies - (this, fargs.ProjectFile, groupedExtensions); + (Project, fargs.ProjectFile, groupedExtensions); if (files != null) filesToAdd.AddRange (files); if (IsWebConfig (fargs.ProjectFile.FilePath)) webConfigChange = true; } - + if (webConfigChange) UpdateWebConfigRefs (); - + //let the base fire the event before we add files //don't want to fire events out of order of files being added base.OnFileAddedToProject (e); - + //make sure that the parent and child files are in the project foreach (string file in filesToAdd) { //NOTE: this only adds files if they are not already in the project - AddFile (file); + Project.AddFile (file); } } - - public override string GetDefaultBuildAction (string fileName) + + protected override string OnGetDefaultBuildAction (string fileName) { - + WebSubtype type = DetermineWebSubtype (fileName); switch (type) { case WebSubtype.Code: return BuildAction.Compile; case WebSubtype.None: - return base.GetDefaultBuildAction (fileName); + return base.OnGetDefaultBuildAction (fileName); default: return BuildAction.Content; } } - + static string[] groupedExtensions = { ".aspx", ".master", ".ashx", ".ascx", ".asmx", ".asax" }; - + #endregion - + public virtual IEnumerable<string> GetSpecialDirectories () { yield return "App_Browsers"; @@ -598,12 +579,12 @@ namespace MonoDevelop.AspNet.Projects yield return "Models"; yield return "Controllers"; } - + // For "web site" projects // "App_WebReferences", "App_Resources","App_Themes", "App_Code", } - - protected override IList<string> GetCommonBuildActions () + + protected override IList<string> OnGetCommonBuildActions () { return new [] { BuildAction.None, @@ -612,7 +593,7 @@ namespace MonoDevelop.AspNet.Projects BuildAction.EmbeddedResource, }; } - + public string GetCodebehindTypeName (string fileName) { lock (codebehindTypeNameCache) @@ -624,8 +605,8 @@ namespace MonoDevelop.AspNet.Projects var files = new List<string> (); var names = new HashSet<string> (); - string asmDir = Path.GetDirectoryName (typeof (AspNetAppProject).Assembly.Location); - string lang = LanguageName; + string asmDir = Path.GetDirectoryName (GetType().Assembly.Location); + string lang = Project.LanguageName; if (lang == "C#") { lang = "CSharp"; } @@ -635,8 +616,8 @@ namespace MonoDevelop.AspNet.Projects } var dirs = new [] { - Path.Combine (BaseDirectory, "CodeTemplates", type), - Path.Combine (BaseDirectory, "CodeTemplates", lang, type), + Path.Combine (Project.BaseDirectory, "CodeTemplates", type), + Path.Combine (Project.BaseDirectory, "CodeTemplates", lang, type), Path.Combine (asmDir, "CodeTemplates", type), Path.Combine (asmDir, "CodeTemplates", lang, type), }; @@ -650,12 +631,12 @@ namespace MonoDevelop.AspNet.Projects return files; } - protected override void PopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) + protected override void OnPopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) { - base.PopulateSupportFileList (list, configuration); + base.OnPopulateSupportFileList (list, configuration); //HACK: workaround for MD not local-copying package references - foreach (MonoDevelop.Projects.ProjectReference projectReference in References) { + foreach (MonoDevelop.Projects.ProjectReference projectReference in Project.References) { if (projectReference.Package != null && projectReference.Package.Name == "system.web.mvc") { if (projectReference.ReferenceType == ReferenceType.Package) foreach (SystemAssembly assem in projectReference.Package.Assemblies) @@ -667,7 +648,7 @@ namespace MonoDevelop.AspNet.Projects public string GetAspNetMvcVersion () { - foreach (var pref in References) { + foreach (var pref in Project.References) { if (pref.Reference.IndexOf ("System.Web.Mvc", StringComparison.OrdinalIgnoreCase) < 0) continue; switch (pref.ReferenceType) { @@ -692,7 +673,7 @@ namespace MonoDevelop.AspNet.Projects public bool SupportsRazorViewEngine { get { - return References.Any (r => r.Reference.StartsWith ("System.Web.WebPages.Razor", StringComparison.Ordinal)); + return Project.References.Any (r => r.Reference.StartsWith ("System.Web.WebPages.Razor", StringComparison.Ordinal)); } } @@ -703,7 +684,7 @@ namespace MonoDevelop.AspNet.Projects public virtual bool IsAspMvcProject { get { - return References.Any (r => r.Reference.StartsWith ("System.Web.Mvc", StringComparison.Ordinal)); + return Project.References.Any (r => r.Reference.StartsWith ("System.Web.Mvc", StringComparison.Ordinal)); } } diff --git a/main/src/addins/AspNet/Projects/AspNetMvcFileTemplateCondition.cs b/main/src/addins/AspNet/Projects/AspNetMvcFileTemplateCondition.cs index 0a4f581ad1..58a71c5371 100644 --- a/main/src/addins/AspNet/Projects/AspNetMvcFileTemplateCondition.cs +++ b/main/src/addins/AspNet/Projects/AspNetMvcFileTemplateCondition.cs @@ -50,7 +50,7 @@ namespace MonoDevelop.AspNet.Projects if (proj == null)
return true;
- var aspProj = proj as AspNetAppProject;
+ var aspProj = proj.GetFlavor<AspNetFlavor> ();
if (aspProj == null)
return false;
diff --git a/main/src/addins/AspNet/Properties/MonoDevelop.AspNet.addin.xml b/main/src/addins/AspNet/Properties/MonoDevelop.AspNet.addin.xml index 17406e444f..a6f13d0f3d 100644 --- a/main/src/addins/AspNet/Properties/MonoDevelop.AspNet.addin.xml +++ b/main/src/addins/AspNet/Properties/MonoDevelop.AspNet.addin.xml @@ -178,32 +178,23 @@ extensions = "*.htm,*.html"/>
</Extension>
- <Extension path = "/MonoDevelop/ProjectModel/ProjectBindings">
- <ProjectBinding id = "AspNetApp" class = "MonoDevelop.AspNet.Projects.AspNetAppProjectBinding" />
- </Extension>
-
- <Extension path = "/MonoDevelop/ProjectModel/MSBuildItemTypes">
- <DotNetProjectSubtype
+ <Extension path = "/MonoDevelop/ProjectModel/ProjectModelExtensions">
+ <ProjectExtension
guid="{603C0E0B-DB56-11DC-BE95-000D561079B0}"
- type="MonoDevelop.AspNet.Projects.AspMvc1Project"
- useXBuild="true" />
- <DotNetProjectSubtype
+ type="MonoDevelop.AspNet.Projects.AspMvc1ProjectExtension" />
+ <ProjectExtension
guid="{F85E285D-A4E0-4152-9332-AB1D724D3325}"
- type="MonoDevelop.AspNet.Projects.AspMvc2Project"
- useXBuild="true" />
- <DotNetProjectSubtype
+ type="MonoDevelop.AspNet.Projects.AspMvc2ProjectExtension" />
+ <ProjectExtension
guid="{E53F8FEA-EAE0-44A6-8774-FFD645390401}"
- type="MonoDevelop.AspNet.Projects.AspMvc3Project"
- useXBuild="true" />
- <DotNetProjectSubtype
+ type="MonoDevelop.AspNet.Projects.AspMvc3ProjectExtension" />
+ <ProjectExtension
guid="{E3E379DF-F4C6-4180-9B81-6769533ABE47}"
- type="MonoDevelop.AspNet.Projects.AspMvc4Project"
- useXBuild="true" />
- <DotNetProjectSubtype
- id="MonoDevelop.AspNet.Projects.AspNetAppProject"
+ type="MonoDevelop.AspNet.Projects.AspMvc4ProjectExtension" />
+ <ProjectExtension
+ id="MonoDevelop.AspNet.Projects.AspNetAppProjectExtension"
guid="{349C5851-65DF-11DA-9384-00065B846F21}"
- type="MonoDevelop.AspNet.Projects.AspNetAppProject"
- useXBuild="true" />
+ type="MonoDevelop.AspNet.Projects.AspNetAppProjectExtension" />
</Extension>
<Extension path = "/MonoDevelop/TypeSystem/Parser">
@@ -217,7 +208,7 @@ </Extension>
<Extension path = "/MonoDevelop/ProjectModel/Gui/ItemOptionPanels/Run">
- <Condition id="ItemType" value="MonoDevelop.AspNet.Projects.AspNetAppProject">
+ <Condition id="FlavorType" value="MonoDevelop.AspNet.Projects.AspNetFlavor">
<Section id = "XspOptions"
_label = "XSP Web Server"
class = "MonoDevelop.AspNet.Execution.XspOptionsPanel"/>
@@ -262,11 +253,9 @@ </Extension>
<Extension path = "/MonoDevelop/Ide/ContextMenu/ProjectPad/Add">
- <Condition id="ItemType" value="MonoDevelop.AspNet.Projects.AspNetAppProject">
- <ItemSet id = "AspNetDirectories" _label = "ASP.NET Directory" insertafter = "MonoDevelop.Ide.Commands.ProjectCommands.NewFolder" autohide = "true">
- <CommandItem id = "MonoDevelop.AspNet.Commands.AspNetCommands.AddAspNetDirectory" />
- </ItemSet>
- </Condition>
+ <ItemSet id = "AspNetDirectories" _label = "ASP.NET Directory" insertafter = "MonoDevelop.Ide.Commands.ProjectCommands.NewFolder" autohide = "true">
+ <CommandItem id = "MonoDevelop.AspNet.Commands.AspNetCommands.AddAspNetDirectory" />
+ </ItemSet>
</Extension>
<Extension path = "/MonoDevelop/Ide/ContextMenu/ProjectPad/Add">
diff --git a/main/src/addins/AspNet/Razor/Generator/RazorTemplatePreprocessor.cs b/main/src/addins/AspNet/Razor/Generator/RazorTemplatePreprocessor.cs index 32a8a31ff2..41d105e862 100644 --- a/main/src/addins/AspNet/Razor/Generator/RazorTemplatePreprocessor.cs +++ b/main/src/addins/AspNet/Razor/Generator/RazorTemplatePreprocessor.cs @@ -30,6 +30,7 @@ using System.CodeDom.Compiler; using MonoDevelop.Projects; using MonoDevelop.Core; using MonoDevelop.TextTemplating; +using System.Threading.Tasks; namespace MonoDevelop.AspNet.Razor.Generator { @@ -46,18 +47,18 @@ namespace MonoDevelop.AspNet.Razor.Generator return ns; } - public IAsyncOperation Generate (IProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) + public Task Generate (ProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) { - return new ThreadAsyncOperation (delegate { + return Task.Factory.StartNew (delegate { try { GenerateInternal (monitor, file, result); } catch (Exception ex) { result.UnhandledException = ex; } - }, result); + }); } - void GenerateInternal (IProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) + void GenerateInternal (ProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) { var dnp = file.Project as DotNetProject; if (dnp == null || dnp.LanguageName != "C#") { diff --git a/main/src/addins/AspNet/Razor/RazorCSharpParser.cs b/main/src/addins/AspNet/Razor/RazorCSharpParser.cs index ac77e93f69..390e00e819 100644 --- a/main/src/addins/AspNet/Razor/RazorCSharpParser.cs +++ b/main/src/addins/AspNet/Razor/RazorCSharpParser.cs @@ -64,7 +64,7 @@ namespace MonoDevelop.AspNet.Razor ChangeInfo lastChange; string lastParsedFile; TextDocument currentDocument; - AspNetAppProject aspProject; + AspNetFlavor aspProject; DotNetProject project; IList<TextDocument> openDocuments; @@ -90,7 +90,7 @@ namespace MonoDevelop.AspNet.Razor if (currentDocument == null && !TryAddDocument (fileName)) return new RazorCSharpParsedDocument (fileName, new RazorCSharpPageInfo ()); - this.aspProject = project as AspNetAppProject; + this.aspProject = project.GetService<AspNetFlavor> (); EnsureParserInitializedFor (fileName); @@ -211,7 +211,7 @@ namespace MonoDevelop.AspNet.Razor // Try to create host using web.config file var webConfigMap = new WebConfigurationFileMap (); if (aspProject != null) { - var vdm = new VirtualDirectoryMapping (aspProject.BaseDirectory.Combine ("Views"), true, "web.config"); + var vdm = new VirtualDirectoryMapping (project.BaseDirectory.Combine ("Views"), true, "web.config"); webConfigMap.VirtualDirectories.Add ("/", vdm); } Configuration configuration; diff --git a/main/src/addins/AspNet/Tests/Razor/RazorCompletionTesting.cs b/main/src/addins/AspNet/Tests/Razor/RazorCompletionTesting.cs index 7da98546eb..d35f5f9ca5 100644 --- a/main/src/addins/AspNet/Tests/Razor/RazorCompletionTesting.cs +++ b/main/src/addins/AspNet/Tests/Razor/RazorCompletionTesting.cs @@ -92,7 +92,7 @@ namespace MonoDevelop.AspNet.Tests.Razor cursorPosition = endPos - 1;
}
- var project = new AspNetAppProject ("C#");
+ var project = Services.ProjectService.CreateDotNetProject ("C#");
project.FileName = UnitTests.TestBase.GetTempFile (".csproj");
string file = UnitTests.TestBase.GetTempFile (extension);
diff --git a/main/src/addins/AspNet/Tests/WebForms/WebFormsTesting.cs b/main/src/addins/AspNet/Tests/WebForms/WebFormsTesting.cs index 4f8e2444d9..74f486803c 100644 --- a/main/src/addins/AspNet/Tests/WebForms/WebFormsTesting.cs +++ b/main/src/addins/AspNet/Tests/WebForms/WebFormsTesting.cs @@ -69,7 +69,7 @@ namespace MonoDevelop.AspNet.Tests.WebForms cursorPosition = endPos - 1; } - var project = new AspNetAppProject ("C#"); + var project = Services.ProjectService.CreateDotNetProject ("C#"); project.References.Add (new ProjectReference (ReferenceType.Package, "System")); project.References.Add (new ProjectReference (ReferenceType.Package, "System.Web")); project.FileName = UnitTests.TestBase.GetTempFile (".csproj"); diff --git a/main/src/addins/AspNet/WebForms/MasterContentFileDescriptionTemplate.cs b/main/src/addins/AspNet/WebForms/MasterContentFileDescriptionTemplate.cs index bced906b6d..8ca2ded55d 100644 --- a/main/src/addins/AspNet/WebForms/MasterContentFileDescriptionTemplate.cs +++ b/main/src/addins/AspNet/WebForms/MasterContentFileDescriptionTemplate.cs @@ -38,7 +38,7 @@ namespace MonoDevelop.AspNet.WebForms { public class MasterContentFileDescriptionTemplate : SingleFileDescriptionTemplate { - public override void ModifyTags (SolutionItem policyParent, Project project, string language, string identifier, string fileName, ref Dictionary<string,string> tags) + public override void ModifyTags (SolutionFolderItem policyParent, Project project, string language, string identifier, string fileName, ref Dictionary<string,string> tags) { base.ModifyTags (policyParent, project, language, identifier, fileName, ref tags); if (fileName == null) @@ -47,13 +47,13 @@ namespace MonoDevelop.AspNet.WebForms tags ["AspNetMaster"] = ""; tags ["AspNetMasterContent"] = ""; - AspNetAppProject aspProj = project as AspNetAppProject; + var aspProj = project.GetService<AspNetFlavor> (); if (aspProj == null) throw new InvalidOperationException ("MasterContentFileDescriptionTemplate is only valid for ASP.NET projects"); ProjectFile masterPage = null; - var dialog = new MonoDevelop.Ide.Projects.ProjectFileSelectorDialog (aspProj, null, "*.master"); + var dialog = new MonoDevelop.Ide.Projects.ProjectFileSelectorDialog (project, null, "*.master"); try { dialog.Title = GettextCatalog.GetString ("Select a Master Page..."); int response = MonoDevelop.Ide.MessageService.RunCustomDialog (dialog); diff --git a/main/src/addins/AspNet/WebForms/WebFormsCodeBehind.cs b/main/src/addins/AspNet/WebForms/WebFormsCodeBehind.cs index bfdce9399f..ed1977dc84 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsCodeBehind.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsCodeBehind.cs @@ -47,7 +47,7 @@ namespace MonoDevelop.AspNet.WebForms { public static string GetCodeBehindClassName (ProjectFile file) { - AspNetAppProject proj = file.Project as AspNetAppProject; + var proj = file.Project.GetService<AspNetFlavor> (); if (proj == null) return null; return proj.GetCodebehindTypeName (file.Name); @@ -55,19 +55,19 @@ namespace MonoDevelop.AspNet.WebForms public static ProjectFile GetDesignerFile (ProjectFile file) { - var project = file.Project as AspNetAppProject; + var ext = file.Project.GetService<AspNetFlavor> (); - var type = AspNetAppProject.DetermineWebSubtype (file.FilePath); + var type = AspNetFlavor.DetermineWebSubtype (file.FilePath); if (type != WebSubtype.WebForm && type != WebSubtype.WebControl && type != WebSubtype.MasterPage) return null; - var dfName = project.LanguageBinding.GetFileName (file.FilePath + ".designer"); - return project.Files.GetFile (dfName); + var dfName = ext.Project.LanguageBinding.GetFileName (file.FilePath + ".designer"); + return ext.Project.Files.GetFile (dfName); } public static BuildResult UpdateDesignerFile ( CodeBehindWriter writer, - AspNetAppProject project, + DotNetProject project, ProjectFile file, ProjectFile designerFile ) { @@ -102,7 +102,7 @@ namespace MonoDevelop.AspNet.WebForms } public static BuildResult GenerateCodeBehind ( - AspNetAppProject project, + DotNetProject project, string filename, WebFormsParsedDocument document, out CodeCompileUnit ccu) @@ -149,7 +149,8 @@ namespace MonoDevelop.AspNet.WebForms masterTypeName = document.Info.MasterPageTypeName; } else if (!String.IsNullOrEmpty (document.Info.MasterPageTypeVPath)) { try { - ProjectFile resolvedMaster = project.ResolveVirtualPath (document.Info.MasterPageTypeVPath, document.FileName); + var ext = project.GetService<AspNetFlavor> (); + ProjectFile resolvedMaster = ext.ResolveVirtualPath (document.Info.MasterPageTypeVPath, document.FileName); WebFormsParsedDocument masterParsedDocument = null; if (resolvedMaster != null) masterParsedDocument = TypeSystemService.ParseFile (project, resolvedMaster.FilePath) as WebFormsParsedDocument; diff --git a/main/src/addins/AspNet/WebForms/WebFormsCodeBehindTypeNameCache.cs b/main/src/addins/AspNet/WebForms/WebFormsCodeBehindTypeNameCache.cs index 526911a74f..c5088a67b6 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsCodeBehindTypeNameCache.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsCodeBehindTypeNameCache.cs @@ -31,13 +31,14 @@ using MonoDevelop.Core; using MonoDevelop.Ide.TypeSystem; using MonoDevelop.Ide; using MonoDevelop.AspNet.WebForms;
-using MonoDevelop.AspNet.Projects; +using MonoDevelop.AspNet.Projects;
+using MonoDevelop.Projects; namespace MonoDevelop.AspNet.WebForms { - class WebFormsCodeBehindTypeNameCache : ProjectFileCache<AspNetAppProject,string> + class WebFormsCodeBehindTypeNameCache : ProjectFileCache<Project,string> { - public WebFormsCodeBehindTypeNameCache (AspNetAppProject proj) : base (proj) + public WebFormsCodeBehindTypeNameCache (Project proj) : base (proj) { } diff --git a/main/src/addins/AspNet/WebForms/WebFormsDirectiveCompletion.cs b/main/src/addins/AspNet/WebForms/WebFormsDirectiveCompletion.cs index 54839d53ae..a7ded63cf7 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsDirectiveCompletion.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsDirectiveCompletion.cs @@ -36,6 +36,7 @@ using System.Web.UI; using MonoDevelop.Core; using MonoDevelop.Ide.CodeCompletion; using MonoDevelop.AspNet.Projects; +using MonoDevelop.Projects; namespace MonoDevelop.AspNet.WebForms { @@ -94,7 +95,7 @@ namespace MonoDevelop.AspNet.WebForms } - public static CompletionDataList GetAttributeValues (AspNetAppProject project, FilePath fromFile, string directiveName, string attribute) + public static CompletionDataList GetAttributeValues (DotNetProject project, FilePath fromFile, string directiveName, string attribute) { switch (directiveName.ToLowerInvariant ()) { case "page": @@ -105,7 +106,7 @@ namespace MonoDevelop.AspNet.WebForms return null; } - public static CompletionDataList GetAttributes (AspNetAppProject project, string directiveName, + public static CompletionDataList GetAttributes (DotNetProject project, string directiveName, Dictionary<string, string> existingAtts) { var list = new CompletionDataList (); @@ -199,7 +200,7 @@ namespace MonoDevelop.AspNet.WebForms list.Add (s); } - static CompletionDataList GetPageAttributeValues (AspNetAppProject project, FilePath fromFile, string attribute) + static CompletionDataList GetPageAttributeValues (Project project, FilePath fromFile, string attribute) { var list = new CompletionDataList (); switch (attribute.ToLowerInvariant ()) { @@ -346,7 +347,7 @@ namespace MonoDevelop.AspNet.WebForms return list.Count > 0? list : null; } - static CompletionDataList GetRegisterAttributeValues (AspNetAppProject project, FilePath fromFile, string attribute) + static CompletionDataList GetRegisterAttributeValues (Project project, FilePath fromFile, string attribute) { switch (attribute.ToLowerInvariant ()) { case "src": diff --git a/main/src/addins/AspNet/WebForms/WebFormsEditorExtension.cs b/main/src/addins/AspNet/WebForms/WebFormsEditorExtension.cs index 96a0239b78..bc2cc3ef64 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsEditorExtension.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsEditorExtension.cs @@ -48,6 +48,7 @@ using S = MonoDevelop.Xml.Parser; using MonoDevelop.AspNet.WebForms.Dom; using MonoDevelop.Xml.Parser; using MonoDevelop.Xml.Dom; +using MonoDevelop.Projects; namespace MonoDevelop.AspNet.WebForms { @@ -56,7 +57,7 @@ namespace MonoDevelop.AspNet.WebForms static readonly Regex DocTypeRegex = new Regex (@"(?:PUBLIC|public)\s+""(?<fpi>[^""]*)""\s+""(?<uri>[^""]*)"""); WebFormsParsedDocument aspDoc; - AspNetAppProject project; + DotNetProject project; WebFormsTypeContext refman = new WebFormsTypeContext (); ILanguageCompletionBuilder documentBuilder; @@ -90,7 +91,7 @@ namespace MonoDevelop.AspNet.WebForms if (HasDoc) refman.Doc = aspDoc; - var newProj = Document.Project as AspNetAppProject; + var newProj = Document.Project as DotNetProject; if (newProj != null) { project = newProj; refman.Project = newProj; diff --git a/main/src/addins/AspNet/WebForms/WebFormsParser.cs b/main/src/addins/AspNet/WebForms/WebFormsParser.cs index 03f19b91be..f29967ff7d 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsParser.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsParser.cs @@ -67,7 +67,7 @@ namespace MonoDevelop.AspNet.WebForms XDocument xDoc = parser.Nodes.GetRoot (); info.Populate (xDoc, errors); - var type = AspNetAppProject.DetermineWebSubtype (fileName); + var type = AspNetFlavor.DetermineWebSubtype (fileName); if (type != info.Subtype) { if (info.Subtype == WebSubtype.None) { errors.Add (new Error (ErrorType.Error, "File directive is missing", 1, 1)); diff --git a/main/src/addins/AspNet/WebForms/WebFormsRegistrationCache.cs b/main/src/addins/AspNet/WebForms/WebFormsRegistrationCache.cs index ac1a6ccb6c..494eae7723 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsRegistrationCache.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsRegistrationCache.cs @@ -38,9 +38,9 @@ using MonoDevelop.AspNet.Projects; namespace MonoDevelop.AspNet.WebForms { - class WebFormsRegistrationCache : ProjectFileCache<AspNetAppProject,RegistrationInfo> + class WebFormsRegistrationCache : ProjectFileCache<DotNetProject,RegistrationInfo> { - public WebFormsRegistrationCache (AspNetAppProject project) : base (project) + public WebFormsRegistrationCache (DotNetProject project) : base (project) { } @@ -135,6 +135,16 @@ namespace MonoDevelop.AspNet.WebForms info.Namespaces.AddRange (defaultNamespaces.Select (ns => new NamespaceRegistration (true, ns))); info.Assemblies.AddRange (defaultAssemblies.Select (asm => new AssemblyRegistration (true, asm))); + + // from Mono's 4.5 machine web.config + info.Controls.AddRange (new [] { + MachineControlReg ("asp", "System.Web.UI.WebControls.WebParts", "System.Web"), + MachineControlReg ("asp", "System.Web.UI", "System.Web.Extensions"), + MachineControlReg ("asp", "System.Web.UI.WebControls", "System.Web.Extensions"), + MachineControlReg ("asp", "System.Web.UI.WebControls.Expressions", "System.Web.Extensions"), + MachineControlReg ("asp", "System.Web.DynamicData", "System.Web.DynamicData"), + MachineControlReg ("asp", "System.Web.UI.WebControls", "System.Web.Entity"), + }); return info; } @@ -171,6 +181,11 @@ namespace MonoDevelop.AspNet.WebForms "System.Web.UI.WebControls.WebParts", }; + static ControlRegistration MachineControlReg(string prefix, string ns, string asm) + { + return new ControlRegistration (null, true, prefix, ns, asm, null, null); + } + public static bool IsDefaultReference (string reference) { return defaultAssemblies.Any (r => diff --git a/main/src/addins/AspNet/WebForms/WebFormsToolboxNode.cs b/main/src/addins/AspNet/WebForms/WebFormsToolboxNode.cs index 6ccccbddc5..f0804abf65 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsToolboxNode.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsToolboxNode.cs @@ -157,7 +157,7 @@ namespace MonoDevelop.AspNet.WebForms public bool IsCompatibleWith (MonoDevelop.Ide.Gui.Document document)
{ - switch (AspNetAppProject.DetermineWebSubtype (document.FileName)) { + switch (AspNetFlavor.DetermineWebSubtype (document.FileName)) { case WebSubtype.WebForm: case WebSubtype.MasterPage: case WebSubtype.WebControl: @@ -167,7 +167,7 @@ namespace MonoDevelop.AspNet.WebForms } var clrVersion = ClrVersion.Net_2_0; - var aspProj = document.Project as AspNetAppProject; + var aspProj = document.Project as DotNetProject; if (aspProj != null && aspProj.TargetFramework.ClrVersion != ClrVersion.Default) clrVersion = aspProj.TargetFramework.ClrVersion; diff --git a/main/src/addins/AspNet/WebForms/WebFormsTypeContext.cs b/main/src/addins/AspNet/WebForms/WebFormsTypeContext.cs index 7778cf5844..5af1c706a6 100644 --- a/main/src/addins/AspNet/WebForms/WebFormsTypeContext.cs +++ b/main/src/addins/AspNet/WebForms/WebFormsTypeContext.cs @@ -51,8 +51,9 @@ namespace MonoDevelop.AspNet.WebForms public class WebFormsTypeContext { ICompilation compilation; - AspNetAppProject project; + DotNetProject project; WebFormsParsedDocument doc; + AspNetFlavor aspFlavor; public WebFormsParsedDocument Doc { get { @@ -66,7 +67,7 @@ namespace MonoDevelop.AspNet.WebForms } } - public AspNetAppProject Project { + public DotNetProject Project { get { return project; } @@ -75,6 +76,7 @@ namespace MonoDevelop.AspNet.WebForms return; project = value; compilation = null; + aspFlavor = project.GetFlavor<AspNetFlavor> (); } } @@ -336,7 +338,7 @@ namespace MonoDevelop.AspNet.WebForms IList<RegistrationInfo> GetRegistrationInfos () { if (project != null && doc != null) - return project.RegistrationCache.GetInfosForPath (Path.GetDirectoryName (doc.FileName)); + return aspFlavor.RegistrationCache.GetInfosForPath (Path.GetDirectoryName (doc.FileName)); return new[] { WebFormsRegistrationCache.MachineRegistrationInfo }; } @@ -570,7 +572,10 @@ namespace MonoDevelop.AspNet.WebForms IType AssemblyTypeLookup (string namespac, string tagName) { var fullName = namespac + "." + tagName; - return ReflectionHelper.ParseReflectionName (fullName).Resolve (Compilation); + var type = ReflectionHelper.ParseReflectionName (fullName).Resolve (Compilation); + if (type.Kind == TypeKind.Unknown) + return null; + return type; } public string GetControlPrefix (IType control) @@ -595,8 +600,8 @@ namespace MonoDevelop.AspNet.WebForms { string typeName = null; if (project != null && doc != null) { - string absolute = project.VirtualToLocalPath (virtualPath, doc.FileName); - typeName = project.GetCodebehindTypeName (absolute); + string absolute = aspFlavor.VirtualToLocalPath (virtualPath, doc.FileName); + typeName = aspFlavor.GetCodebehindTypeName (absolute); } return typeName ?? "System.Web.UI.UserControl"; } @@ -604,7 +609,10 @@ namespace MonoDevelop.AspNet.WebForms IType GetUserControlType (string virtualPath) { var name = GetUserControlTypeName (virtualPath); - return ReflectionHelper.ParseReflectionName (name).Resolve (Compilation); + var type = ReflectionHelper.ParseReflectionName (name).Resolve (Compilation); + if (type.Kind == TypeKind.Unknown) + return null; + return type; } } diff --git a/main/src/addins/CBinding/CBinding.addin.xml b/main/src/addins/CBinding/CBinding.addin.xml index 35cb77e26d..1fef8d00e9 100644 --- a/main/src/addins/CBinding/CBinding.addin.xml +++ b/main/src/addins/CBinding/CBinding.addin.xml @@ -190,12 +190,6 @@ <CommandItem id = "MonoDevelop.Ide.Commands.EditCommands.Delete"/> </Extension> - <Extension path = "/MonoDevelop/ProjectModel/ProjectServiceExtensions"> - <Condition id="ItemType" value="CBinding.CProject"> - <Class id = "ExtraSteps" class = "CBinding.CProjectServiceExtension"/> - </Condition> - </Extension> - <Extension path = "/MonoDevelop/Ide/TextEditorExtensions"> <Class fileExtensions=".c,.cpp,.cxx,.cc,.h,.hpp,.hh,.hxx,.m,.mm,.M" class = "CBinding.CTextEditorExtension" /> </Extension> @@ -207,11 +201,7 @@ <DataType class = "CBinding.GppCompiler"/> <DataType class = "CBinding.Package"/> </Extension> - - <Extension path = "/MonoDevelop/ProjectModel/MSBuildItemTypes"> - <SolutionItem type="CBinding.CProject" extension="cproj" guid="{2857B73E-F847-4B02-9238-064979017E93}"/> - </Extension> - + <!-- Current Autotools AddIn is very .NET specific <Module> <Runtime> diff --git a/main/src/addins/CBinding/CBinding.csproj b/main/src/addins/CBinding/CBinding.csproj index 94f0eb7bb6..7962736351 100644 --- a/main/src/addins/CBinding/CBinding.csproj +++ b/main/src/addins/CBinding/CBinding.csproj @@ -200,7 +200,6 @@ </ItemGroup> <ItemGroup> <Compile Include="Project\CProject.cs" /> - <Compile Include="Project\CProjectBinding.cs" /> <Compile Include="Project\CProjectConfiguration.cs" /> <Compile Include="gtk-gui\generated.cs" /> <Compile Include="Gui\CodeGenerationPanel.cs" /> @@ -220,7 +219,6 @@ <Compile Include="Project\ProjectPackageEventArgs.cs" /> <Compile Include="Gui\OutputOptionsPanel.cs" /> <Compile Include="gtk-gui\CBinding.OutputOptionsPanel.cs" /> - <Compile Include="Project\CProjectServiceExtension.cs" /> <Compile Include="Navigation\ProjectNodeBuilderExtension.cs" /> <Compile Include="Navigation\NamespaceNodeBuilder.cs" /> <Compile Include="ProjectPad\ProjectReferencesExtension.cs" /> diff --git a/main/src/addins/CBinding/Compiler/CCompiler.cs b/main/src/addins/CBinding/Compiler/CCompiler.cs index b094faf03f..4a92d92bc2 100644 --- a/main/src/addins/CBinding/Compiler/CCompiler.cs +++ b/main/src/addins/CBinding/Compiler/CCompiler.cs @@ -75,9 +75,9 @@ namespace CBinding ProjectFileCollection projectFiles, ProjectPackageCollection packages, CProjectConfiguration configuration, - IProgressMonitor monitor); + ProgressMonitor monitor); - public abstract void Clean (ProjectFileCollection projectFiles, CProjectConfiguration configuration, IProgressMonitor monitor); + public abstract void Clean (ProjectFileCollection projectFiles, CProjectConfiguration configuration, ProgressMonitor monitor); protected abstract void ParseCompilerOutput (string errorString, CompilerResults cr); diff --git a/main/src/addins/CBinding/Compiler/GNUCompiler.cs b/main/src/addins/CBinding/Compiler/GNUCompiler.cs index b75471a9ff..be4a0bc5f8 100644 --- a/main/src/addins/CBinding/Compiler/GNUCompiler.cs +++ b/main/src/addins/CBinding/Compiler/GNUCompiler.cs @@ -56,7 +56,7 @@ namespace CBinding ProjectFileCollection projectFiles, ProjectPackageCollection packages, CProjectConfiguration configuration, - IProgressMonitor monitor) + ProgressMonitor monitor) { if (!appsChecked) { appsChecked = true; @@ -271,7 +271,7 @@ namespace CBinding private bool PrecompileHeaders (ProjectFileCollection projectFiles, CProjectConfiguration configuration, string args, - IProgressMonitor monitor, + ProgressMonitor monitor, CompilerResults cr) { monitor.BeginTask (GettextCatalog.GetString ("Precompiling headers"), 1); @@ -303,7 +303,7 @@ namespace CBinding return success; } - private bool DoPrecompileHeader (ProjectFile file, string output, string args, IProgressMonitor monitor, CompilerResults cr) + private bool DoPrecompileHeader (ProjectFile file, string output, string args, ProgressMonitor monitor, CompilerResults cr) { string completeArgs = String.Format ("\"{0}\" {1} -o {2}", file.Name, args, output); string errorOutput; @@ -353,7 +353,7 @@ namespace CBinding CProjectConfiguration configuration, ProjectPackageCollection packages, CompilerResults cr, - IProgressMonitor monitor, string outputName) + ProgressMonitor monitor, string outputName) { if (!NeedsUpdate (projectFiles, configuration, outputName)) return; @@ -406,7 +406,7 @@ namespace CBinding CProjectConfiguration configuration, ProjectPackageCollection packages, CompilerResults cr, - IProgressMonitor monitor, string outputName) + ProgressMonitor monitor, string outputName) { if (!NeedsUpdate (projectFiles, configuration, outputName)) return; @@ -431,7 +431,7 @@ namespace CBinding CProjectConfiguration configuration, ProjectPackageCollection packages, CompilerResults cr, - IProgressMonitor monitor, string outputName) + ProgressMonitor monitor, string outputName) { if (!NeedsUpdate (projectFiles, configuration, outputName)) return; @@ -479,7 +479,7 @@ namespace CBinding CheckReturnCode (exitCode, cr); } - int ExecuteCommand (string command, string args, string baseDirectory, IProgressMonitor monitor, out string errorOutput) + int ExecuteCommand (string command, string args, string baseDirectory, ProgressMonitor monitor, out string errorOutput) { errorOutput = string.Empty; int exitCode = -1; @@ -491,23 +491,20 @@ namespace CBinding monitor.Log.WriteLine ("{0} {1}", command, args); - using (var operationMonitor = new AggregatedOperationMonitor (monitor)) { - using (ProcessWrapper p = Runtime.ProcessService.StartProcess (command, args, baseDirectory, monitor.Log, chainedError, null)) { - operationMonitor.AddOperation (p); //handles cancellation - - p.WaitForOutput (); - chainedError.UnchainWriter (monitor.Log); - chainedError.UnchainWriter (swError); + using (ProcessWrapper p = Runtime.ProcessService.StartProcess (command, args, baseDirectory, monitor.Log, chainedError, null)) + using (monitor.CancellationToken.Register (p.Cancel)) { + p.WaitForOutput (); + chainedError.UnchainWriter (monitor.Log); + chainedError.UnchainWriter (swError); - errorOutput = swError.ToString (); - exitCode = p.ExitCode; - - if (monitor.IsCancelRequested) { - monitor.Log.WriteLine (GettextCatalog.GetString ("Build cancelled")); - monitor.ReportError (GettextCatalog.GetString ("Build cancelled"), null); - if (exitCode == 0) - exitCode = -1; - } + errorOutput = swError.ToString (); + exitCode = p.ExitCode; + + if (monitor.CancellationToken.IsCancellationRequested) { + monitor.Log.WriteLine (GettextCatalog.GetString ("Build cancelled")); + monitor.ReportError (GettextCatalog.GetString ("Build cancelled"), null); + if (exitCode == 0) + exitCode = -1; } } } @@ -542,7 +539,7 @@ namespace CBinding private bool DoCompilation (ProjectFile file, CProjectConfiguration configuration, string args, - IProgressMonitor monitor, + ProgressMonitor monitor, CompilerResults cr, bool use_ccache) { @@ -605,7 +602,7 @@ namespace CBinding return objectFiles.ToArray (); } - public override void Clean (ProjectFileCollection projectFiles, CProjectConfiguration configuration, IProgressMonitor monitor) + public override void Clean (ProjectFileCollection projectFiles, CProjectConfiguration configuration, ProgressMonitor monitor) { //clean up object files foreach (string oFile in ObjectFiles(projectFiles, configuration, false)) { diff --git a/main/src/addins/CBinding/Compiler/ICompiler.cs b/main/src/addins/CBinding/Compiler/ICompiler.cs index edb2b80c96..a3b7ad7a0e 100644 --- a/main/src/addins/CBinding/Compiler/ICompiler.cs +++ b/main/src/addins/CBinding/Compiler/ICompiler.cs @@ -69,8 +69,8 @@ namespace CBinding ProjectFileCollection projectFiles, ProjectPackageCollection packages, CProjectConfiguration configuration, - IProgressMonitor monitor); + ProgressMonitor monitor); - void Clean (ProjectFileCollection projectFiles, CProjectConfiguration configuration, IProgressMonitor monitor); + void Clean (ProjectFileCollection projectFiles, CProjectConfiguration configuration, ProgressMonitor monitor); } } diff --git a/main/src/addins/CBinding/Gui/EditPackagesDialog.cs b/main/src/addins/CBinding/Gui/EditPackagesDialog.cs index d7cd1f8adb..b43001e1b3 100644 --- a/main/src/addins/CBinding/Gui/EditPackagesDialog.cs +++ b/main/src/addins/CBinding/Gui/EditPackagesDialog.cs @@ -192,7 +192,7 @@ namespace CBinding List<Package> packages = new List<Package>(); Package package; - foreach (SolutionItem c in project.ParentFolder.Items) { + foreach (SolutionFolderItem c in project.ParentFolder.Items) { if (null != c && c is CProject) { CProject cproj = (CProject)c; CProjectConfiguration conf = (CProjectConfiguration)cproj.GetConfiguration (IdeApp.Workspace.ActiveConfiguration); diff --git a/main/src/addins/CBinding/Project/CProject.cs b/main/src/addins/CBinding/Project/CProject.cs index 231830b4f0..79e1bc2535 100644 --- a/main/src/addins/CBinding/Project/CProject.cs +++ b/main/src/addins/CBinding/Project/CProject.cs @@ -46,6 +46,7 @@ using MonoDevelop.Deployment; using MonoDevelop.Deployment.Linux; using CBinding.Parser; using MonoDevelop.Ide; +using System.Threading.Tasks; namespace CBinding { @@ -62,8 +63,8 @@ namespace CBinding ShowPackageDetails, GotoDeclaration, } - - [DataInclude(typeof(CProjectConfiguration))] + + [RegisterProjectType ("{2857B73E-F847-4B02-9238-064979017E93}", Extension="cproj", Alias="C/C++")] public class CProject : Project, IDeployable { [ItemProperty ("Compiler", ValueType = typeof(CCompiler))] @@ -177,9 +178,9 @@ namespace CBinding } } - public override IEnumerable<string> GetProjectTypes () + protected override void OnGetProjectTypes (HashSet<string> types) { - yield return "Native"; + types.Add ("Native"); } public override string[] SupportedLanguages { @@ -202,7 +203,7 @@ namespace CBinding } } - public override IEnumerable<SolutionItem> GetReferencedItems (ConfigurationSelector configuration) + protected override IEnumerable<SolutionItem> OnGetReferencedItems (ConfigurationSelector configuration) { foreach (var p in base.GetReferencedItems (configuration)) yield return p; @@ -302,15 +303,33 @@ namespace CBinding return pkgfile; } - protected override BuildResult DoBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> DoBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { CProjectConfiguration pc = (CProjectConfiguration) GetConfiguration (configuration); pc.SourceDirectory = BaseDirectory; - - return compiler_manager.Compile (this, - Files, packages, - pc, - monitor); + + return Task<BuildResult>.Factory.StartNew (delegate { + if (pc.CompileTarget != CompileTarget.Bin) + WriteMDPkgPackage (configuration); + + return compiler_manager.Compile (this, + Files, packages, + pc, + monitor); + }); + } + + protected async override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + CProjectConfiguration conf = (CProjectConfiguration) GetConfiguration (configuration); + + var res = await base.OnClean (monitor, configuration); + if (res.HasErrors) + return res; + + await Task.Factory.StartNew (() => Compiler.Clean (Files, conf, monitor)); + + return res; } protected virtual ExecutionCommand CreateExecutionCommand (CProjectConfiguration conf) @@ -330,7 +349,7 @@ namespace CBinding return (target == CBinding.CompileTarget.Bin) && context.ExecutionHandler.CanExecute (cmd); } - protected override void DoExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + protected async override Task DoExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { CProjectConfiguration conf = (CProjectConfiguration) GetConfiguration (configuration); bool pause = conf.PauseConsoleOutput; @@ -348,26 +367,22 @@ namespace CBinding else console = context.ConsoleFactory.CreateConsole (!pause); - AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor (monitor); - try { ExecutionCommand cmd = CreateExecutionCommand (conf); if (!context.ExecutionHandler.CanExecute (cmd)) { monitor.ReportError ("Cannot execute \"" + conf.Output + "\". The selected execution mode is not supported for C projects.", null); return; } - - IProcessAsyncOperation op = context.ExecutionHandler.Execute (cmd, console); - - operationMonitor.AddOperation (op); - op.WaitForCompleted (); + + ProcessAsyncOperation op = context.ExecutionHandler.Execute (cmd, console); + using (var t = monitor.CancellationToken.Register (op.Cancel)) + await op.Task; monitor.Log.WriteLine ("The operation exited with code: {0}", op.ExitCode); } catch (Exception ex) { LoggingService.LogError (string.Format ("Cannot execute \"{0}\"", conf.Output), ex); monitor.ReportError ("Cannot execute \"" + conf.Output + "\"", ex); } finally { - operationMonitor.Dispose (); console.Dispose (); } } diff --git a/main/src/addins/CBinding/Project/CProjectBinding.cs b/main/src/addins/CBinding/Project/CProjectBinding.cs deleted file mode 100644 index db379d8763..0000000000 --- a/main/src/addins/CBinding/Project/CProjectBinding.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// CProjectBinding.cs: binding with the CProject -// -// Authors: -// Marcos David Marin Amador <MarcosMarin@gmail.com> -// -// Copyright (C) 2007 Marcos David Marin Amador -// -// -// This source code is licenced under The MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System.Xml; -using System.IO; - -using Mono.Addins; - -using MonoDevelop.Projects; - -namespace CBinding -{ - public class CProjectBinding : IProjectBinding - { - public string Name { - get { return "C/C++"; } - } - - public Project CreateProject (ProjectCreateInformation info, - XmlElement projectOptions) - { - string language = projectOptions.GetAttribute ("language"); - return new CProject (info, projectOptions, language); - } - - public Project CreateSingleFileProject (string sourceFile) - { - var info = new ProjectCreateInformation () { - ProjectName = Path.GetFileNameWithoutExtension (sourceFile), - SolutionPath = Path.GetDirectoryName (sourceFile), - ProjectBasePath = Path.GetDirectoryName (sourceFile), - }; - - Project project = new CProject (info, null, GetLanguage (sourceFile)); - project.Files.Add (new ProjectFile (sourceFile)); - return project; - } - - string GetLanguage (string filename) - { - switch (Path.GetExtension (filename.ToLower ())) { - case ".c": - return "C"; - case ".cpp": - case ".cxx": - return "CPP"; - default: - return null; - } - } - - public bool CanCreateSingleFileProject (string sourceFile) - { - return GetLanguage (sourceFile) != null; - } - } -} diff --git a/main/src/addins/CBinding/Project/CProjectServiceExtension.cs b/main/src/addins/CBinding/Project/CProjectServiceExtension.cs deleted file mode 100644 index 22775dc090..0000000000 --- a/main/src/addins/CBinding/Project/CProjectServiceExtension.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -// CProjectServiceExtension.cs -// -// Authors: -// Marcos David Marin Amador <MarcosMarin@gmail.com> -// -// Copyright (C) 2007 Marcos David Marin Amador -// -// -// This source code is licenced under The MIT License: -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -using System; -using System.IO; -using System.Text; - -using Mono.Addins; - -using MonoDevelop.Core; -using MonoDevelop.Projects; -using MonoDevelop.Core.Execution; - -namespace CBinding -{ - public class CProjectServiceExtension : ProjectServiceExtension - { - public override bool SupportsItem (IBuildTarget item) - { - return item is CProject; - } - - protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) - { - CProject project = (CProject) entry; - CProjectConfiguration conf = (CProjectConfiguration) project.GetConfiguration (configuration); - if (conf.CompileTarget != CompileTarget.Bin) - project.WriteMDPkgPackage (configuration); - - return base.Build (monitor, entry, configuration); - } - - protected override void Clean (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) - { - base.Clean (monitor, entry, configuration); - - CProject project = (CProject) entry; - CProjectConfiguration conf = (CProjectConfiguration) project.GetConfiguration (configuration); - project.Compiler.Clean (project.Files, conf, monitor); - } - } -} diff --git a/main/src/addins/CBinding/ProjectPad/ProjectPackageNodeBuilder.cs b/main/src/addins/CBinding/ProjectPad/ProjectPackageNodeBuilder.cs index 6c460d9aac..42cbc28768 100644 --- a/main/src/addins/CBinding/ProjectPad/ProjectPackageNodeBuilder.cs +++ b/main/src/addins/CBinding/ProjectPad/ProjectPackageNodeBuilder.cs @@ -81,7 +81,7 @@ namespace CBinding.ProjectPad project.Packages.Remove (package); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); } public override DragOperation CanDragNode () diff --git a/main/src/addins/CBinding/ProjectPad/ProjectPackagesFolderNodeBuilder.cs b/main/src/addins/CBinding/ProjectPad/ProjectPackagesFolderNodeBuilder.cs index dc3dd1e117..9e86d90b68 100644 --- a/main/src/addins/CBinding/ProjectPad/ProjectPackagesFolderNodeBuilder.cs +++ b/main/src/addins/CBinding/ProjectPad/ProjectPackagesFolderNodeBuilder.cs @@ -35,6 +35,8 @@ using MonoDevelop.Components.Commands; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Components; using MonoDevelop.Ide; +using MonoDevelop.Projects; +using System.Collections.Generic; namespace CBinding.ProjectPad { @@ -132,7 +134,7 @@ namespace CBinding.ProjectPad MessageService.ShowCustomDialog (new EditPackagesDialog (project)); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); CurrentNode.Expanded = true; } @@ -164,6 +166,7 @@ namespace CBinding.ProjectPad public override void OnNodeDrop (object dataObject, DragOperation operation) { + List<IWorkspaceFileObject> toSave = new List<IWorkspaceFileObject> (); if (dataObject is Package) { Package package = (Package)dataObject; ITreeNavigator nav = CurrentNode; @@ -173,11 +176,11 @@ namespace CBinding.ProjectPad CProject source = nav.GetParentDataItem (typeof(CProject), true) as CProject; dest.Packages.Add (package); - IdeApp.ProjectOperations.Save (dest); - + toSave.Add (dest); + if (operation == DragOperation.Move) { source.Packages.Remove (package); - IdeApp.ProjectOperations.Save (source); + toSave.Add (source); } } else if (dataObject is CProject) { CProject draggedProject = (CProject)dataObject; @@ -189,9 +192,10 @@ namespace CBinding.ProjectPad if (!destProject.Packages.Contains (package)) { destProject.Packages.Add (package); - IdeApp.ProjectOperations.Save (destProject); + toSave.Add (destProject); } } + IdeApp.ProjectOperations.SaveAsync (toSave); } } } diff --git a/main/src/addins/CSharpBinding/AspNet/ASPNetReferenceFinder.cs b/main/src/addins/CSharpBinding/AspNet/ASPNetReferenceFinder.cs index 1484fe7b1d..ec6553f68a 100644 --- a/main/src/addins/CSharpBinding/AspNet/ASPNetReferenceFinder.cs +++ b/main/src/addins/CSharpBinding/AspNet/ASPNetReferenceFinder.cs @@ -58,7 +58,7 @@ namespace MonoDevelop.CSharp.Refactoring // yield return new DomRegion (fileName, loc.Line, loc.Column, loc.Line, loc.Column + result.Name.Lenhth); // } } - public override IEnumerable<MemberReference> FindReferences (MonoDevelop.Projects.Project project, IProjectContent content, IEnumerable<FilePath> files, IProgressMonitor monitor, IEnumerable<object> searchedMembers) + public override IEnumerable<MemberReference> FindReferences (MonoDevelop.Projects.Project project, IProjectContent content, IEnumerable<FilePath> files, ProgressMonitor monitor, IEnumerable<object> searchedMembers) { // TODO: Type system conversion. yield break; // var editor = TextFileProvider.Instance.GetTextEditorData (fileName); diff --git a/main/src/addins/CSharpBinding/Autotools/CSharpAutotoolsSetup.cs b/main/src/addins/CSharpBinding/Autotools/CSharpAutotoolsSetup.cs index 3e08162ea7..9df0ae112b 100644 --- a/main/src/addins/CSharpBinding/Autotools/CSharpAutotoolsSetup.cs +++ b/main/src/addins/CSharpBinding/Autotools/CSharpAutotoolsSetup.cs @@ -43,7 +43,7 @@ namespace CSharpBinding.Autotools if ( config == null ) return ""; CSharpCompilerParameters parameters = (CSharpCompilerParameters) config.CompilationParameters; - CSharpProjectParameters projectParameters = (CSharpProjectParameters) config.ProjectParameters; + ICSharpProject projectParameters = config.ParentItem.GetService<ICSharpProject> (); StringWriter writer = new StringWriter(); diff --git a/main/src/addins/CSharpBinding/CSharpBinding.addin.xml b/main/src/addins/CSharpBinding/CSharpBinding.addin.xml index 8ac2fe8f96..6531dabcbe 100644 --- a/main/src/addins/CSharpBinding/CSharpBinding.addin.xml +++ b/main/src/addins/CSharpBinding/CSharpBinding.addin.xml @@ -10,21 +10,18 @@ </Extension> <Extension path = "/MonoDevelop/ProjectModel/MSBuildItemTypes"> - <DotNetProject + <DotNetProjectType language="C#" extension="csproj" guid="{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" import="$(MSBuildBinPath)\Microsoft.CSharp.targets" - resourceHandler="MonoDevelop.CSharp.Project.CSharpResourceIdBuilder" + type="MonoDevelop.CSharp.Project.CSharpProject" /> + </Extension> + + <Extension path = "/MonoDevelop/ProjectModel/ProjectModelExtensions"> <Condition id="MSBuildTargetIsAvailable" target="$(MSBuildExtensionsPath)\Microsoft\Portable\v4.0\Microsoft.Portable.CSharp.targets"> - <DotNetProjectSubtype - guid="{786C830F-07A1-408B-BD7F-6EE04809D6DB}" - type="MonoDevelop.Projects.PortableDotNetProject" - useXBuild="true"> - <AddImport language="C#" projects="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" /> - <RemoveImport language="C#" projects="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> - </DotNetProjectSubtype> + <ProjectFlavor guid="{786C830F-07A1-408B-BD7F-6EE04809D6DB}" type="MonoDevelop.CSharp.Project.PortableCSharpProjectFlavor" /> </Condition> </Extension> diff --git a/main/src/addins/CSharpBinding/CSharpBinding.csproj b/main/src/addins/CSharpBinding/CSharpBinding.csproj index 180eb11cbd..5c449f40fb 100644 --- a/main/src/addins/CSharpBinding/CSharpBinding.csproj +++ b/main/src/addins/CSharpBinding/CSharpBinding.csproj @@ -222,7 +222,6 @@ <Compile Include="MonoDevelop.CSharp.Formatting\CSharpFormattingPolicyPanel.cs" /> <Compile Include="MonoDevelop.CSharp.Formatting\CSharpFormatter.cs" /> <Compile Include="MonoDevelop.CSharp.Project\CSharpCompilerParameters.cs" /> - <Compile Include="MonoDevelop.CSharp.Project\CSharpProjectParameters.cs" /> <Compile Include="MonoDevelop.CSharp.Project\CSharpResourceIdBuilder.cs" /> <Compile Include="MonoDevelop.CSharp.Project\CodeGenerationPanel.cs" /> <Compile Include="MonoDevelop.CSharp.Project\CompilerOptionsPanelWidget.cs" /> @@ -313,6 +312,8 @@ <Compile Include="MonoDevelop.CSharp.CodeGeneration\ExportCodeGenerator.cs" /> <Compile Include="MonoDevelop.CSharp.Completion\MonoCSharpCompletionEngine.cs" /> <Compile Include="MonoDevelop.CSharp.Completion\ProtocolCompletionData.cs" /> + <Compile Include="MonoDevelop.CSharp.Project\CSharpProjectExtension.cs" /> + <Compile Include="MonoDevelop.CSharp.Project\PortableCSharpProjectFlavor.cs" /> </ItemGroup> <ItemGroup> <None Include="Makefile.am" /> diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs index cdac91156d..316fa9aab4 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Completion/CSharpCompletionTextEditorExtension.cs @@ -58,6 +58,7 @@ using MonoDevelop.CSharp.Project; using MonoDevelop.CSharp.Formatting; using MonoDevelop.CSharp.Refactoring.CodeActions; using MonoDevelop.Refactoring; +using System.Xml; namespace MonoDevelop.CSharp.Completion { @@ -147,13 +148,16 @@ namespace MonoDevelop.CSharp.Completion public CSharpCompletionTextEditorExtension () { } - + + bool addEventHandlersInInitialization = true; + /// <summary> /// Used in testing environment. /// </summary> [System.ComponentModel.Browsable(false)] - public CSharpCompletionTextEditorExtension (MonoDevelop.Ide.Gui.Document doc) : this () + public CSharpCompletionTextEditorExtension (MonoDevelop.Ide.Gui.Document doc, bool addEventHandlersInInitialization = true) : this () { + this.addEventHandlersInInitialization = addEventHandlersInInitialization; Initialize (doc); } @@ -165,10 +169,12 @@ namespace MonoDevelop.CSharp.Completion this.Unit = parsedDocument.GetAst<SyntaxTree> (); this.UnresolvedFileCompilation = Document.Compilation; this.CSharpUnresolvedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile; - document.Editor.Caret.PositionChanged += HandlePositionChanged; + if (addEventHandlersInInitialization) + document.Editor.Caret.PositionChanged += HandlePositionChanged; } - - Document.DocumentParsed += HandleDocumentParsed; + + if (addEventHandlersInInitialization) + Document.DocumentParsed += HandleDocumentParsed; } CancellationTokenSource src = new CancellationTokenSource (); diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs index 87898df7e1..fce4666569 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs @@ -580,6 +580,7 @@ namespace MonoDevelop.CSharp.Formatting int lastNonWsOffset = caretOffset; char lastNonWsChar = '\0'; outOffset = caretOffset; + int max = curLine.EndOffset; int end = caretOffset; @@ -595,69 +596,22 @@ namespace MonoDevelop.CSharp.Formatting return false; } - bool isInString = false, isInChar = false, isVerbatimString = false; - bool isInLineComment = false, isInBlockComment = false; - bool firstChar = true; - for (int pos = caretOffset; pos < max; pos++) { - if (pos == caretOffset) { - if (isInString || isInChar || isVerbatimString || isInLineComment || isInBlockComment) { - outOffset = pos; - return true; - } - } - char ch = data.Document.GetCharAt (pos); - switch (ch) { - case '}': - if (firstChar && !IsSemicolonalreadyPlaced (data, caretOffset)) - return false; - break; - case '/': - if (isInBlockComment) { - isInBlockComment &= pos <= 0 || data.Document.GetCharAt (pos - 1) != '*'; - } else if (!isInString && !isInChar && pos + 1 < max) { - char nextChar = data.Document.GetCharAt (pos + 1); - if (nextChar == '/') { - outOffset = lastNonWsOffset; - return true; - } - if (!isInLineComment && nextChar == '*') { - outOffset = lastNonWsOffset; - return true; - } - } - break; - case '\\': - if (isInChar || (isInString && !isVerbatimString)) - pos++; - break; - case '@': - if (!(isInString || isInChar || isInLineComment || isInBlockComment) && pos + 1 < max && data.Document.GetCharAt (pos + 1) == '"') { - isInString = true; - isVerbatimString = true; - pos++; - } - break; - case '"': - if (!(isInChar || isInLineComment || isInBlockComment)) { - if (isInString && isVerbatimString && pos + 1 < max && data.Document.GetCharAt (pos + 1) == '"') { - pos++; - } else { - isInString = !isInString; - isVerbatimString = false; - } - } - break; - case '\'': - if (!(isInString || isInLineComment || isInBlockComment)) - isInChar = !isInChar; - break; + var offset = curLine.Offset; + string lineText = data.GetTextAt (caretOffset, max - caretOffset); + var lexer = new CSharpCompletionEngineBase.MiniLexer (lineText); + lexer.Parse ((ch, i) => { + if (lexer.IsInSingleComment || lexer.IsInMultiLineComment) + return true; + if (ch == '}' && lexer.IsFistNonWs && !IsSemicolonalreadyPlaced (data, caretOffset)) { + lastNonWsChar = ';'; + return true; } if (!char.IsWhiteSpace (ch)) { - firstChar = false; - lastNonWsOffset = pos; + lastNonWsOffset = caretOffset + i; lastNonWsChar = ch; } - } + return false; + }); // if the line ends with ';' the line end is not the correct place for a new semicolon. if (lastNonWsChar == ';') return false; diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs index 998368be6a..76fa3cf026 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs @@ -281,6 +281,54 @@ namespace MonoDevelop.CSharp.Highlighting } tree.AddStyle (startOffset, endOffset, color); } + + public override void VisitSimpleType (SimpleType simpleType) + { + var identifierToken = simpleType.IdentifierToken; + VisitChildrenUntil(simpleType, identifierToken); + var resolveResult = resolver.Resolve (simpleType, cancellationToken); + if (resolveResult.Type.Namespace == "System") { + switch (resolveResult.Type.Name) { + case "nfloat": + case "nint": + case "nuint": + Colorize(identifierToken, "Keyword(Type)"); + break; + default: + Colorize (identifierToken, resolveResult); + break; + } + } else { + Colorize (identifierToken, resolveResult); + } + VisitChildrenAfter(simpleType, identifierToken); + } + + public override void VisitIdentifierExpression (IdentifierExpression identifierExpression) + { + var identifier = identifierExpression.IdentifierToken; + VisitChildrenUntil(identifierExpression, identifier); + if (isInAccessorContainingValueParameter && identifierExpression.Identifier == "value") { + Colorize(identifier, valueKeywordColor); + } else { + var resolveResult = resolver.Resolve (identifierExpression, cancellationToken); + if (resolveResult.Type.Namespace == "System") { + switch (resolveResult.Type.Name) { + case "nfloat": + case "nint": + case "nuint": + Colorize(identifier, "Keyword(Type)"); + break; + default: + Colorize (identifier, resolveResult); + break; + } + } else { + Colorize (identifier, resolveResult); + } + } + VisitChildrenAfter(identifierExpression, identifier); + } } class QuickTaskVisitor : DepthFirstAstVisitor diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Parser/TypeSystemProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Parser/TypeSystemProvider.cs index 475fac0ee1..0192f4a3e7 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Parser/TypeSystemProvider.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Parser/TypeSystemProvider.cs @@ -84,7 +84,13 @@ namespace MonoDevelop.CSharp.Parser result.ParsedFile = pf; result.Add (GetSemanticTags (unit)); - result.CreateRefactoringContext = (doc, token) => MDRefactoringContext.Create (doc, doc.Editor.Caret.Location, token).Result; + result.CreateRefactoringContext = delegate (MonoDevelop.Ide.Gui.Document doc, System.Threading.CancellationToken token) { + var task = MDRefactoringContext.Create (doc, doc.Editor.Caret.Location, token); + task.Wait (5000, token); + if (!task.IsCompleted) + return null; + return task.Result; + }; result.CreateRefactoringContextWithEditor = (data, resolver, token) => new MDRefactoringContext ((DotNetProject)project, data, result, (CSharpAstResolver)resolver, TextLocation.Empty, token); if (storeAst) { diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpCompilerParameters.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpCompilerParameters.cs index 6c528ba8f4..0f0ca7f675 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpCompilerParameters.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpCompilerParameters.cs @@ -33,6 +33,7 @@ using MonoDevelop.Core.Serialization; using MonoDevelop.Core; using Mono.Collections.Generic; using System.Linq; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.CSharp.Project { @@ -48,7 +49,7 @@ namespace MonoDevelop.CSharp.Project /// <summary> /// This class handles project specific compiler parameters /// </summary> - public class CSharpCompilerParameters: DotNetConfigurationParameters + public class CSharpCompilerParameters: DotNetCompilerParameters { // Configuration parameters @@ -91,60 +92,26 @@ namespace MonoDevelop.CSharp.Project [ItemProperty("DebugType", DefaultValue="")] string debugType = ""; - #region Members required for backwards compatibility. Not used for anything else. - - [ItemProperty ("StartupObject", DefaultValue = null)] - internal string mainclass; - - [ProjectPathItemProperty ("ApplicationIcon", DefaultValue = null)] - internal string win32Icon; - - [ProjectPathItemProperty ("Win32Resource", DefaultValue = null)] - internal string win32Resource; - - [ItemProperty ("CodePage", DefaultValue = null)] - internal string codePage; + protected override void Write (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + base.Write (pset, format); + pset.SetPropertyOrder ("DebugSymbols", "DebugType", "Optimize", "OutputPath", "DefineConstants", "ErrorReport", "WarningLevel", "TreatWarningsAsErrors", "DocumentationFile"); + pset.WriteObjectProperties (this, typeof(CSharpCompilerParameters)); + } - [ItemProperty ("GenerateDocumentation", DefaultValue = null)] - bool? generateXmlDocumentation = null; - - #endregion - - - protected override void OnEndLoad () + protected override void Read (IMSBuildPropertySet pset, MSBuildFileFormat format) { - base.OnEndLoad (); - - // Backwards compatibility. Move parameters to the project parameters object - if (ParentConfiguration != null && ParentConfiguration.ProjectParameters != null) { - CSharpProjectParameters cparams = (CSharpProjectParameters) ParentConfiguration.ProjectParameters; - if (win32Icon != null) { - cparams.Win32Icon = win32Icon; - win32Icon = null; - } - if (win32Resource != null) { - cparams.Win32Resource = win32Resource; - win32Resource = null; - } - if (mainclass != null) { - cparams.MainClass = mainclass; - mainclass = null; - } - if (!string.IsNullOrEmpty (codePage)) { - cparams.CodePage = int.Parse (codePage); - codePage = null; - } - } + base.Read (pset, format); + pset.ReadObjectProperties (this, typeof(CSharpCompilerParameters)); - if (generateXmlDocumentation.HasValue && ParentConfiguration != null) { - if (generateXmlDocumentation.Value) + var prop = pset.GetProperty ("GenerateDocumentation"); + if (prop != null && documentationFile != null) { + if (prop.GetValue<bool> ()) documentationFile = ParentConfiguration.CompiledOutputName.ChangeExtension (".xml"); else documentationFile = null; - generateXmlDocumentation = null; } } - public LangVersion LangVersion { get { diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpProjectExtension.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpProjectExtension.cs new file mode 100644 index 0000000000..5c66cf0c2d --- /dev/null +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpProjectExtension.cs @@ -0,0 +1,149 @@ +// +// CSharpProjectExtension.cs +// +// Author: +// Lluis Sanchez Gual <lluis@xamarin.com> +// +// Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using MonoDevelop.Projects; +using MonoDevelop.Projects.Formats.MSBuild; +using MonoDevelop.Core; +using MonoDevelop.Core.Serialization; +using MonoDevelop.Projects.Extensions; +using System.Collections.Generic; + +namespace MonoDevelop.CSharp.Project +{ + class CSharpProject: DotNetProject, ICSharpProject + { + [ItemProperty ("StartupObject", DefaultValue = "")] + string mainclass = string.Empty; + + [ProjectPathItemProperty ("ApplicationIcon", DefaultValue = "")] + string win32Icon = String.Empty; + + [ProjectPathItemProperty ("Win32Resource", DefaultValue = "")] + string win32Resource = String.Empty; + + [ItemProperty ("CodePage", DefaultValue = 0)] + int codePage; + + static CSharpResourceIdBuilder resourceHandler = new CSharpResourceIdBuilder (); + + public CSharpProject () + { + Initialize (this); + DefaultImports.Add ("$(MSBuildBinPath)\\Microsoft.CSharp.targets"); + } + + public string MainClass { + get { + return mainclass; + } + set { + mainclass = value ?? string.Empty; + } + } + + public int CodePage { + get { + return codePage; + } + set { + codePage = value; + } + } + + public string Win32Icon { + get { + return win32Icon; + } + set { + win32Icon = value ?? string.Empty; + } + } + + public string Win32Resource { + get { + return win32Resource; + } + set { + win32Resource = value ?? string.Empty; + } + } + + protected override object OnGetService (Type t) + { + if (t == typeof(IResourceHandler)) + return resourceHandler; + return base.GetService (t); + } + + protected override void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject) + { + base.OnWriteProject (monitor, msproject); + msproject.GetGlobalPropertyGroup ().WriteObjectProperties (this, typeof(CSharpProject)); + } + + protected override void OnReadProject (ProgressMonitor monitor, MSBuildProject msproject) + { + base.OnReadProject (monitor, msproject); + msproject.GetGlobalPropertyGroup ().ReadObjectProperties (this, typeof(CSharpProject)); + } + + protected override void OnReadConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet pset) + { + base.OnReadConfiguration (monitor, config, pset); + + // Backwards compatibility. Move parameters to the project parameters object + + var prop = pset.GetProperty ("ApplicationIcon"); + if (prop != null) + win32Icon = prop.GetPathValue (); + + prop = pset.GetProperty ("Win32Resource"); + if (prop != null) + win32Resource = prop.GetPathValue (); + + prop = pset.GetProperty ("StartupObject"); + if (prop != null) + mainclass = prop.Value; + + prop = pset.GetProperty ("CodePage"); + if (prop != null) + codePage = int.Parse (prop.Value); + } + } + + public interface ICSharpProject + { + string MainClass { get; set; } + + int CodePage { get; set; } + + string Win32Icon { get; set; } + + string Win32Resource { get; set; } + } + +} + diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CompilerOptionsPanelWidget.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CompilerOptionsPanelWidget.cs index 21300b94a3..465f0e95f2 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CompilerOptionsPanelWidget.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CompilerOptionsPanelWidget.cs @@ -53,7 +53,7 @@ namespace MonoDevelop.CSharp.Project this.project = project; DotNetProjectConfiguration configuration = (DotNetProjectConfiguration) project.GetConfiguration (IdeApp.Workspace.ActiveConfiguration); CSharpCompilerParameters compilerParameters = (CSharpCompilerParameters) configuration.CompilationParameters; - CSharpProjectParameters projectParameters = (CSharpProjectParameters) configuration.ProjectParameters; + var csproject = (CSharpProject)project; ListStore store = new ListStore (typeof (string));
store.AppendValues (GettextCatalog.GetString ("Executable"));
@@ -75,7 +75,7 @@ namespace MonoDevelop.CSharp.Project classListStore = new ListStore (typeof(string));
mainClassEntry.Model = classListStore;
mainClassEntry.TextColumn = 0;
- ((Entry)mainClassEntry.Child).Text = projectParameters.MainClass ?? string.Empty; + ((Entry)mainClassEntry.Child).Text = csproject.MainClass ?? string.Empty; UpdateTarget (); } @@ -85,16 +85,16 @@ namespace MonoDevelop.CSharp.Project foreach (TextEncoding e in TextEncoding.SupportedEncodings) { if (e.CodePage == -1) continue; - if (e.CodePage == projectParameters.CodePage) + if (e.CodePage == csproject.CodePage) foundEncoding = e.Id; codepageEntry.AppendText (e.Id); } if (foundEncoding != null) codepageEntry.Entry.Text = foundEncoding; - else if (projectParameters.CodePage != 0) - codepageEntry.Entry.Text = projectParameters.CodePage.ToString (); + else if (csproject.CodePage != 0) + codepageEntry.Entry.Text = csproject.CodePage.ToString (); - iconEntry.Path = projectParameters.Win32Icon; + iconEntry.Path = csproject.Win32Icon; iconEntry.DefaultPath = project.BaseDirectory; allowUnsafeCodeCheckButton.Active = compilerParameters.UnsafeCode; noStdLibCheckButton.Active = compilerParameters.NoStdLib; @@ -171,15 +171,15 @@ namespace MonoDevelop.CSharp.Project project.CompileTarget = compileTarget; - CSharpProjectParameters projectParameters = (CSharpProjectParameters) project.LanguageParameters; + var csproject = (CSharpProject)project; - projectParameters.CodePage = codePage; + csproject.CodePage = codePage; if (iconEntry.Sensitive) - projectParameters.Win32Icon = iconEntry.Path; + csproject.Win32Icon = iconEntry.Path; if (mainClassEntry.Sensitive) - projectParameters.MainClass = mainClassEntry.Entry.Text; + csproject.MainClass = mainClassEntry.Entry.Text; foreach (DotNetProjectConfiguration configuration in configs) { CSharpCompilerParameters compilerParameters = (CSharpCompilerParameters) configuration.CompilationParameters; diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpProjectParameters.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/PortableCSharpProjectFlavor.cs index 7e010c0de6..c7d50c2884 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/CSharpProjectParameters.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Project/PortableCSharpProjectFlavor.cs @@ -1,21 +1,21 @@ -// -// ProjectParameters.cs -// +// +// PortableCSharpProjectFlavor.cs +// // Author: -// Lluis Sanchez Gual <lluis@novell.com> -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// +// Lluis Sanchez Gual <lluis@xamarin.com> +// +// Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.com) +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,62 +23,27 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. - using System; -using MonoDevelop.Core.Serialization; using MonoDevelop.Projects; +using MonoDevelop.Core; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.CSharp.Project { - public class CSharpProjectParameters: ProjectParameters + public class PortableCSharpProjectFlavor: PortableDotNetProjectFlavor { - [ItemProperty ("StartupObject", DefaultValue = "")] - string mainclass = string.Empty; - - [ProjectPathItemProperty ("ApplicationIcon", DefaultValue = "")] - string win32Icon = String.Empty; - - [ProjectPathItemProperty ("Win32Resource", DefaultValue = "")] - string win32Resource = String.Empty; - - [ItemProperty ("CodePage", DefaultValue = 0)] - int codePage; - - public string MainClass { - get { - return mainclass; - } - set { - mainclass = value ?? string.Empty; - } - } - - public int CodePage { - get { - return codePage; - } - set { - codePage = value; - } + protected override void Initialize () + { + base.Initialize (); + Project.UseMSBuildEngine = true; } - - public string Win32Icon { - get { - return win32Icon; - } - set { - win32Icon = value ?? string.Empty; - } - } - - public string Win32Resource { - get { - return win32Resource; - } - set { - win32Resource = value ?? string.Empty; - } + + protected override void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject) + { + base.OnWriteProject (monitor, msproject); + msproject.RemoveImport ("$(MSBuildBinPath)\\Microsoft.CSharp.targets"); + msproject.AddNewImport ("$(MSBuildExtensionsPath32)\\Microsoft\\Portable\\$(TargetFrameworkVersion)\\Microsoft.Portable.CSharp.targets"); } - } } + diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/Actions/MoveTypeToFile.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/Actions/MoveTypeToFile.cs index bf1523421d..d9d8be69ac 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/Actions/MoveTypeToFile.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/Actions/MoveTypeToFile.cs @@ -72,7 +72,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions if (IsSingleType (ctx)) { FileService.RenameFile (ctx.TextEditor.FileName, correctFileName); if (ctx.FileContainerProject != null) - ctx.FileContainerProject.Save (new NullProgressMonitor ()); + ctx.FileContainerProject.Save (new ProgressMonitor ()); return; } @@ -103,7 +103,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions File.WriteAllText (correctFileName, content); context.FileContainerProject.AddFile (correctFileName); - MonoDevelop.Ide.IdeApp.ProjectOperations.Save (context.FileContainerProject); + MonoDevelop.Ide.IdeApp.ProjectOperations.SaveAsync (context.FileContainerProject); } static bool IsBlankLine (TextDocument doc, int i) diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs index a831bc4171..8674904f33 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs @@ -235,7 +235,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions if (sharedResolver == null) return null; return new MDRefactoringContext (document, sharedResolver, loc, cancellationToken); - }, TaskContinuationOptions.ExecuteSynchronously); + }); } internal MDRefactoringContext (Document document, CSharpAstResolver resolver, TextLocation loc, CancellationToken cancellationToken = default (CancellationToken)) : base (resolver, cancellationToken) diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs index 80db3eb8a1..02e35f0e04 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs @@ -269,7 +269,11 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions if (operationsRunning-- == 0) { isDisposed = true; undoGroup.Dispose (); - base.Dispose (); + try { + base.Dispose (); + } catch (Exception e) { + LoggingService.LogError ("Error while disposing refactoring script", e); + } } foreach (var script in startedScripts) script.Dispose (); @@ -363,7 +367,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions if (project != null) { project.AddFile (correctFileName); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); } IdeApp.Workbench.OpenDocument (correctFileName, project); } diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpReferenceFinder.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpReferenceFinder.cs index 950209fcbf..e8e1278ee1 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpReferenceFinder.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpReferenceFinder.cs @@ -285,7 +285,7 @@ namespace MonoDevelop.CSharp.Refactoring return result; } - public override IEnumerable<MemberReference> FindReferences (Project project, IProjectContent content, IEnumerable<FilePath> possibleFiles, IProgressMonitor monitor, IEnumerable<object> members) + public override IEnumerable<MemberReference> FindReferences (Project project, IProjectContent content, IEnumerable<FilePath> possibleFiles, ProgressMonitor monitor, IEnumerable<object> members) { if (content == null) throw new ArgumentNullException ("content", "Project content not set."); diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBindingCompilerManager.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBindingCompilerManager.cs index 363af546b5..c850fda17b 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBindingCompilerManager.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpBindingCompilerManager.cs @@ -55,10 +55,10 @@ namespace MonoDevelop.CSharp sb.AppendLine (); } - public static BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) + public static BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor) { var compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters (); - var projectParameters = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters (); + var projectParameters = (CSharpProject) configuration.ParentItem; FilePath outputName = configuration.CompiledOutputName; string responseFileName = Path.GetTempFileName (); @@ -418,7 +418,7 @@ namespace MonoDevelop.CSharp return result; } - static int DoCompilation (IProgressMonitor monitor, string compilerName, string compilerArgs, string working_dir, ExecutionEnvironment envVars, List<string> gacRoots, ref string output, ref string error) + static int DoCompilation (ProgressMonitor monitor, string compilerName, string compilerArgs, string working_dir, ExecutionEnvironment envVars, List<string> gacRoots, ref string output, ref string error) { output = Path.GetTempFileName (); error = Path.GetTempFileName (); @@ -448,9 +448,9 @@ namespace MonoDevelop.CSharp pinfo.RedirectStandardOutput = true; pinfo.RedirectStandardError = true; - MonoDevelop.Core.Execution.ProcessWrapper pw = Runtime.ProcessService.StartProcess (pinfo, outwr, errwr, null); - using (var mon = new AggregatedOperationMonitor (monitor, pw)) { - pw.WaitForOutput (); + ProcessWrapper pw = Runtime.ProcessService.StartProcess (pinfo, outwr, errwr, null); + using (monitor.CancellationToken.Register (pw.Cancel)) { + pw.Task.Wait (); } int exitCode = pw.ExitCode; bool cancelRequested = pw.CancelRequested;
diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpLanguageBinding.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpLanguageBinding.cs index 968bb4af36..eab17d4f76 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpLanguageBinding.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/CSharpLanguageBinding.cs @@ -72,12 +72,12 @@ namespace MonoDevelop.CSharp return StringComparer.OrdinalIgnoreCase.Equals (Path.GetExtension (fileName), ".cs"); } - public BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) + public BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor) { return CSharpBindingCompilerManager.Compile (projectItems, configuration, configSelector, monitor); } - public ConfigurationParameters CreateCompilationParameters (XmlElement projectOptions) + public DotNetCompilerParameters CreateCompilationParameters (XmlElement projectOptions) { CSharpCompilerParameters pars = new CSharpCompilerParameters (); if (projectOptions != null) { @@ -96,11 +96,6 @@ namespace MonoDevelop.CSharp return pars; } - public ProjectParameters CreateProjectParameters (XmlElement projectOptions) - { - return new CSharpProjectParameters (); - } - public string SingleLineCommentTag { get { return "//"; } } public string BlockCommentStartTag { get { return "/*"; } } public string BlockCommentEndTag { get { return "*/"; } } diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs index 7739ce1084..4484afcad9 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp/PathedDocumentTextEditorExtension.cs @@ -46,6 +46,8 @@ namespace MonoDevelop.CSharp { IdeApp.Workspace.FileAddedToProject -= HandleProjectChanged; IdeApp.Workspace.FileRemovedFromProject -= HandleProjectChanged; + IdeApp.Workspace.WorkspaceItemUnloaded -= HandleWorkspaceItemUnloaded; + IdeApp.Workspace.WorkspaceItemLoaded -= HandleWorkspaceItemLoaded;; if (caret != null) { caret.PositionChanged -= UpdatePath; @@ -65,20 +67,46 @@ namespace MonoDevelop.CSharp Mono.TextEditor.Caret caret; CSharpCompletionTextEditorExtension ext; - List<DotNetProject> ownerProjects; + List<DotNetProject> ownerProjects = new List<DotNetProject> (); public override void Initialize () { CurrentPath = new PathEntry[] { new PathEntry (GettextCatalog.GetString ("No selection")) { Tag = null } }; isPathSet = false; - UpdateOwnerProjects (); - UpdatePath (null, null); + // Delay the execution of UpdateOwnerProjects since it may end calling Document.AttachToProject, + // which shouldn't be called while the extension chain is being initialized. + Gtk.Application.Invoke (delegate { + UpdateOwnerProjects (); + UpdatePath (null, null); + }); caret = Document.Editor.Caret; caret.PositionChanged += UpdatePath; ext = Document.GetContent<CSharpCompletionTextEditorExtension> (); ext.TypeSegmentTreeUpdated += HandleTypeSegmentTreeUpdated; IdeApp.Workspace.FileAddedToProject += HandleProjectChanged; IdeApp.Workspace.FileRemovedFromProject += HandleProjectChanged; + IdeApp.Workspace.WorkspaceItemUnloaded += HandleWorkspaceItemUnloaded; + IdeApp.Workspace.WorkspaceItemLoaded += HandleWorkspaceItemLoaded;; + } + + void HandleWorkspaceItemLoaded (object sender, WorkspaceItemEventArgs e) + { + if (ownerProjects != null) + return; + UpdateOwnerProjects (e.Item.GetAllItems<DotNetProject> ()); + } + + void HandleWorkspaceItemUnloaded (object sender, WorkspaceItemEventArgs e) + { + if (ownerProjects == null) + return; + foreach (var p in e.Item.GetAllItems<DotNetProject> ()) { + ownerProjects.Remove (p); + } + if (ownerProjects.Count == 0) { + ownerProjects = null; + Document.AttachToProject (null); + } } void HandleProjectChanged (object sender, ProjectFileEventArgs e) @@ -92,9 +120,9 @@ namespace MonoDevelop.CSharp UpdatePath (null, null); } - void UpdateOwnerProjects () + void UpdateOwnerProjects (IEnumerable<DotNetProject> allProjects) { - var projects = new HashSet<DotNetProject> (IdeApp.Workspace.GetAllSolutionItems<DotNetProject> ().Where (p => p.IsFileInProject (Document.FileName))); + var projects = new HashSet<DotNetProject> (allProjects.Where (p => p.IsFileInProject (Document.FileName))); if (ownerProjects == null || !projects.SetEquals (ownerProjects)) { ownerProjects = projects.OrderBy (p => p.Name).ToList (); var dnp = Document.Project as DotNetProject; @@ -106,6 +134,11 @@ namespace MonoDevelop.CSharp Document.AttachToProject (pp); } } + } + + void UpdateOwnerProjects () + { + UpdateOwnerProjects (IdeApp.Workspace.GetAllItems<DotNetProject> ()); if (Document.Project == null && ownerProjects.Count > 0) Document.AttachToProject (ownerProjects[0]); } @@ -481,7 +514,7 @@ namespace MonoDevelop.CSharp var curType = (EntityDeclaration)unit.GetNodeAt (loc, n => n is TypeDeclaration || n is DelegateDeclaration); - var curProject = ownerProjects.Count > 1 ? Document.Project : null; + var curProject = ownerProjects != null && ownerProjects.Count > 1 ? Document.Project : null; var segMember = compExt.GetMemberAt (caretOffset); if (segMember != null) { @@ -512,7 +545,7 @@ namespace MonoDevelop.CSharp var result = new List<PathEntry> (); - if (ownerProjects.Count > 1) { + if (ownerProjects != null && ownerProjects.Count > 1) { // Current project if there is more than one result.Add (new PathEntry (ImageService.GetIcon (Document.Project.StockIcon, Gtk.IconSize.Menu), GLib.Markup.EscapeText (Document.Project.Name)) { Tag = Document.Project }); } diff --git a/main/src/addins/CSharpBinding/gtk-gui/gui.stetic b/main/src/addins/CSharpBinding/gtk-gui/gui.stetic index ea86d2e379..ebc8427558 100644 --- a/main/src/addins/CSharpBinding/gtk-gui/gui.stetic +++ b/main/src/addins/CSharpBinding/gtk-gui/gui.stetic @@ -514,6 +514,7 @@ None</property> </widget> <widget class="Gtk.Bin" id="MonoDevelop.CSharp.Project.CompilerOptionsPanelWidget" design-size="471 438"> <property name="MemberName" /> + <property name="GeneratePublic">False</property> <child> <widget class="Gtk.VBox" id="vbox1"> <property name="MemberName" /> diff --git a/main/src/addins/CSharpBinding/templates/PortableLibrary.xpt.xml b/main/src/addins/CSharpBinding/templates/PortableLibrary.xpt.xml index 51a5345be6..a26a237dce 100644 --- a/main/src/addins/CSharpBinding/templates/PortableLibrary.xpt.xml +++ b/main/src/addins/CSharpBinding/templates/PortableLibrary.xpt.xml @@ -24,8 +24,8 @@ <StartupProject>${ProjectName}</StartupProject> </Options> - <Project name = "${ProjectName}" directory = "." type = "PortableDotNet"> - <Options Target = "Library" TargetFrameworkVersion = ".NETPortable,Version=v4.5,Profile=Profile78"/> + <Project name = "${ProjectName}" directory = "."> + <Options Target = "Library" TargetFrameworkVersion = ".NETPortable,Version=v4.5,Profile=Profile78" flavorIds="{786C830F-07A1-408B-BD7F-6EE04809D6DB}"/> <References> </References> <Files> diff --git a/main/src/addins/ChangeLogAddIn/ChangeLogService.cs b/main/src/addins/ChangeLogAddIn/ChangeLogService.cs index 587bb5db7c..25581a2cf2 100644 --- a/main/src/addins/ChangeLogAddIn/ChangeLogService.cs +++ b/main/src/addins/ChangeLogAddIn/ChangeLogService.cs @@ -38,7 +38,7 @@ namespace MonoDevelop.ChangeLogAddIn // Returns the path of the ChangeLog where changes of the provided file have to be logged. // Returns null if no ChangeLog could be found. // Returns an empty string if changes don't have to be logged. - public static string GetChangeLogForFile (string baseCommitPath, FilePath file, out SolutionItem parentEntry, out ChangeLogPolicy policy) + public static string GetChangeLogForFile (string baseCommitPath, FilePath file, out SolutionFolderItem parentEntry, out ChangeLogPolicy policy) { parentEntry = null; policy = null; @@ -50,7 +50,7 @@ namespace MonoDevelop.ChangeLogAddIn string bestPath = null; file = file.CanonicalPath; - foreach (SolutionItem e in IdeApp.Workspace.GetAllSolutionItems ()) { + foreach (SolutionFolderItem e in IdeApp.Workspace.GetAllSolutionItems ()) { if (e is Project && ((Project)e).Files.GetFile (file) != null) { parentEntry = e; break; @@ -108,18 +108,18 @@ namespace MonoDevelop.ChangeLogAddIn public static string GetChangeLogForFile (string baseCommitPath, string file) { - SolutionItem parentEntry; + SolutionFolderItem parentEntry; ChangeLogPolicy policy; return GetChangeLogForFile (baseCommitPath, file, out parentEntry, out policy); } - public static CommitMessageStyle GetMessageStyle (SolutionItem item) + public static CommitMessageStyle GetMessageStyle (SolutionFolderItem item) { ChangeLogPolicy policy = item != null ? GetPolicy (item) : new ChangeLogPolicy (); return policy.MessageStyle; } - static ChangeLogPolicy GetPolicy (SolutionItem item) + static ChangeLogPolicy GetPolicy (SolutionFolderItem item) { return item.Policies.Get<ChangeLogPolicy> (); } diff --git a/main/src/addins/ChangeLogAddIn/CommitDialogExtensionWidget.cs b/main/src/addins/ChangeLogAddIn/CommitDialogExtensionWidget.cs index e5e8b5b266..3b7d78f0b9 100644 --- a/main/src/addins/ChangeLogAddIn/CommitDialogExtensionWidget.cs +++ b/main/src/addins/ChangeLogAddIn/CommitDialogExtensionWidget.cs @@ -156,7 +156,7 @@ namespace MonoDevelop.ChangeLogAddIn } if (!cset.ContainsFile (ce.File)) { if (!cset.Repository.GetVersionInfo (ce.File).IsVersioned) - cset.Repository.Add (ce.File, false, new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor ()); + cset.Repository.Add (ce.File, false, new MonoDevelop.Core.ProgressMonitor ()); cset.AddFile (ce.File); } } @@ -226,7 +226,7 @@ namespace MonoDevelop.ChangeLogAddIn requireComment = false; foreach (ChangeSetItem item in cset.Items) { - SolutionItem parentItem; + SolutionFolderItem parentItem; ChangeLogPolicy policy; string logf = ChangeLogService.GetChangeLogForFile (cset.BaseLocalPath, item.LocalPath, out parentItem, out policy); diff --git a/main/src/addins/ChangeLogAddIn/ProjectOptionPanelWidget.cs b/main/src/addins/ChangeLogAddIn/ProjectOptionPanelWidget.cs index 1492307f2b..777de0e1e4 100644 --- a/main/src/addins/ChangeLogAddIn/ProjectOptionPanelWidget.cs +++ b/main/src/addins/ChangeLogAddIn/ProjectOptionPanelWidget.cs @@ -68,7 +68,7 @@ namespace MonoDevelop.ChangeLogAddIn format.MaxColumns = 70; format.Style = style; - SolutionItem item = null; + SolutionFolderItem item = null; if (parent.ConfiguredSolutionItem != null) item = parent.ConfiguredSolutionItem; else if (parent.ConfiguredSolution != null) diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/BasicOptionPanelWidget.cs b/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/BasicOptionPanelWidget.cs index dd9d2e72cc..e34322c60f 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/BasicOptionPanelWidget.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/BasicOptionPanelWidget.cs @@ -10,9 +10,9 @@ namespace MonoDevelop.Deployment.Linux [System.ComponentModel.ToolboxItem(true)] public partial class BasicOptionPanelWidget : Gtk.Bin { - SolutionItem entry; + SolutionFolderItem entry; - public BasicOptionPanelWidget (SolutionItem entry, bool creatingProject) + public BasicOptionPanelWidget (SolutionFolderItem entry, bool creatingProject) { this.Build(); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxDeployData.cs b/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxDeployData.cs index 255b54257b..2de01203cb 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxDeployData.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxDeployData.cs @@ -22,10 +22,10 @@ namespace MonoDevelop.Deployment.Linux [ItemProperty (DefaultValue=true)] bool generatePcFile = true; - SolutionItem entry; + SolutionFolderItem entry; bool connected; - internal LinuxDeployData (SolutionItem entry) + internal LinuxDeployData (SolutionFolderItem entry) { this.entry = entry; } @@ -34,7 +34,7 @@ namespace MonoDevelop.Deployment.Linux { } - public static LinuxDeployData GetLinuxDeployData (SolutionItem entry) + public static LinuxDeployData GetLinuxDeployData (SolutionFolderItem entry) { LinuxDeployData data = (LinuxDeployData) entry.ExtendedProperties ["Deployment.LinuxDeployData"]; if (data != null) { @@ -55,12 +55,12 @@ namespace MonoDevelop.Deployment.Linux return data; } - internal static LinuxDeployData CreateDefault (SolutionItem entry) + internal static LinuxDeployData CreateDefault (SolutionFolderItem entry) { return new LinuxDeployData (entry); } - void Bind (SolutionItem entry) + void Bind (SolutionFolderItem entry) { this.entry = entry; } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxIntegrationProjectFeature.cs b/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxIntegrationProjectFeature.cs index 74c0f4df37..6d01470859 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxIntegrationProjectFeature.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment.Linux/MonoDevelop.Deployment.Linux/LinuxIntegrationProjectFeature.cs @@ -17,32 +17,30 @@ namespace MonoDevelop.Deployment.Linux get { return GettextCatalog.GetString ("Set options for generating files to better integrate the application or library in a Unix system."); } } - public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionItem entry) + public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionFolderItem entry) { - if (entry is DotNetAssemblyProject) - return FeatureSupportLevel.SupportedByDefault; if (entry is DotNetProject) - return FeatureSupportLevel.Supported; + return FeatureSupportLevel.SupportedByDefault; else return FeatureSupportLevel.NotSupported; } - public bool SupportsSolutionItem (SolutionFolder parentCombine, SolutionItem entry) + public bool SupportsSolutionItem (SolutionFolder parentCombine, SolutionFolderItem entry) { return entry is DotNetProject; } - public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionItem entry) + public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionFolderItem entry) { return new BasicOptionPanelWidget ((DotNetProject) entry, true); } - public void ApplyFeature (SolutionFolder parentCombine, SolutionItem entry, Widget editor) + public void ApplyFeature (SolutionFolder parentCombine, SolutionFolderItem entry, Widget editor) { ((BasicOptionPanelWidget)editor).Store (); } - public string Validate (SolutionFolder parentCombine, SolutionItem entry, Gtk.Widget editor) + public string Validate (SolutionFolder parentCombine, SolutionFolderItem entry, Gtk.Widget editor) { return ((BasicOptionPanelWidget)editor).Validate (); } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Commands/Commands.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Commands/Commands.cs index 9096ae8463..01cf8485c4 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Commands/Commands.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Commands/Commands.cs @@ -18,7 +18,7 @@ namespace MonoDevelop.Deployment { protected override void Run () { - SolutionItem entry = IdeApp.ProjectOperations.CurrentSelectedSolutionItem; + SolutionFolderItem entry = IdeApp.ProjectOperations.CurrentSelectedSolutionItem; DeployDialog dlg = new DeployDialog (entry, false); try { if (MessageService.RunCustomDialog (dlg) == (int) Gtk.ResponseType.Ok) { @@ -33,11 +33,11 @@ namespace MonoDevelop.Deployment project.FileName = Path.Combine (dlg.NewProjectSolution.BaseDirectory, project.Name + ".mdse"); project.Packages.Add (p); dlg.NewProjectSolution.Items.Add (project); - IdeApp.ProjectOperations.Save (dlg.NewProjectSolution.ParentSolution); + IdeApp.ProjectOperations.SaveAsync (dlg.NewProjectSolution.ParentSolution); } else { dlg.ExistingPackagingProject.Packages.Add (p); - IdeApp.ProjectOperations.Save (dlg.ExistingPackagingProject); + IdeApp.ProjectOperations.SaveAsync (dlg.ExistingPackagingProject); } } Package pkg = new Package (dlg.PackageBuilder); @@ -63,7 +63,7 @@ namespace MonoDevelop.Deployment try { if (MessageService.RunCustomDialog (dlg) == (int) Gtk.ResponseType.Ok) { project.AddPackage (dlg.NewPackageName, dlg.PackageBuilder); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); } } finally { dlg.Destroy (); @@ -80,7 +80,7 @@ namespace MonoDevelop.Deployment { protected override void Run () { - SolutionItem entry = IdeApp.ProjectOperations.CurrentSelectedSolutionItem; + SolutionFolderItem entry = IdeApp.ProjectOperations.CurrentSelectedSolutionItem; DeployOperations.Install (entry, IdeApp.Workspace.ActiveConfiguration); } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployDialog.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployDialog.cs index 7fa3039562..4fbe017f7b 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployDialog.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployDialog.cs @@ -7,6 +7,7 @@ using MonoDevelop.Projects; using MonoDevelop.Core; using MonoDevelop.Ide; using MonoDevelop.Components; +using System.Linq; namespace MonoDevelop.Deployment.Gui { @@ -16,11 +17,11 @@ namespace MonoDevelop.Deployment.Gui List<PackageBuilder> builders = new List<PackageBuilder> (); PackageBuilder currentBuilder; Gtk.Widget currentEditor; - ReadOnlyCollection<SolutionFolder> combineList; - ReadOnlyCollection<PackagingProject> projectsList; - SolutionItem defaultEntry; + List<SolutionFolder> combineList; + List<PackagingProject> projectsList; + SolutionFolderItem defaultEntry; - public DeployDialog (SolutionItem defaultEntry, bool createBuilderOnly) + public DeployDialog (SolutionFolderItem defaultEntry, bool createBuilderOnly) { this.Build(); notebook.ShowTabs = false; @@ -104,7 +105,7 @@ namespace MonoDevelop.Deployment.Gui { // Fill the combine list int n=0, sel=-1; - combineList = IdeApp.ProjectOperations.CurrentSelectedSolution.GetAllSolutionItems<SolutionFolder> (); + combineList = IdeApp.ProjectOperations.CurrentSelectedSolution.GetAllItems<SolutionFolder> ().ToList (); foreach (SolutionFolder c in combineList) { string name = c.Name; SolutionFolder co = c; @@ -121,7 +122,7 @@ namespace MonoDevelop.Deployment.Gui comboCreateProject.Active = 0; // Fill the packaging project list - projectsList = IdeApp.ProjectOperations.CurrentSelectedSolution.GetAllSolutionItems<PackagingProject> (); + projectsList = IdeApp.ProjectOperations.CurrentSelectedSolution.GetAllItems<PackagingProject> ().ToList(); if (projectsList.Count == 0) { radioAddProject.Sensitive = false; } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployOperations.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployOperations.cs index 1f877eef1d..74fab9ef93 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployOperations.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/DeployOperations.cs @@ -3,14 +3,15 @@ using System.Collections; using MonoDevelop.Core; using MonoDevelop.Ide; using MonoDevelop.Projects; +using System.Threading.Tasks; namespace MonoDevelop.Deployment.Gui { public static class DeployOperations { - public static void Install (SolutionItem entry, ConfigurationSelector configuration) + public static void Install (SolutionFolderItem entry, ConfigurationSelector configuration) { - using (IProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor ()) { + using (ProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor ()) { InstallDialog dlg = new InstallDialog (entry); try { if (MessageService.RunCustomDialog (dlg) == (int) Gtk.ResponseType.Ok) @@ -21,36 +22,29 @@ namespace MonoDevelop.Deployment.Gui } } - public static IAsyncOperation BuildPackages (PackagingProject project) + public static Task BuildPackages (PackagingProject project) { return BuildPackages (project.Packages); } - static IAsyncOperation BuildPackages (ICollection packages) + static async Task BuildPackages (ICollection packages) { - IProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor (true); + ProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor (true); // Run the deploy command in a background thread to avoid // deadlocks with the gui thread - System.Threading.Thread t = new System.Threading.Thread ( - delegate () { - using (mon) { - mon.BeginTask ("Creating packages", packages.Count); - foreach (Package p in packages) { - DeployService.BuildPackage (mon, p); - mon.Step (1); - } - mon.EndTask (); + using (mon) { + mon.BeginTask ("Creating packages", packages.Count); + foreach (Package p in packages) { + await DeployService.BuildPackage (mon, p); + mon.Step (1); } - }); - t.IsBackground = true; - t.Start (); - - return mon.AsyncOperation; + mon.EndTask (); + } } - public static IAsyncOperation BuildPackage (Package package) + public static Task BuildPackage (Package package) { return BuildPackages (new object[] { package }); } @@ -59,7 +53,7 @@ namespace MonoDevelop.Deployment.Gui { EditPackageDialog dlg = new EditPackageDialog (package); if (MessageService.ShowCustomDialog (dlg) == (int) Gtk.ResponseType.Ok) - IdeApp.ProjectOperations.Save (package.ParentProject); + IdeApp.ProjectOperations.SaveAsync (package.ParentProject); } } } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EditPackageDialog.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EditPackageDialog.cs index 7c2b81062e..58049d30d0 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EditPackageDialog.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EditPackageDialog.cs @@ -54,7 +54,7 @@ namespace MonoDevelop.Deployment.Gui protected virtual void OnEntrySelectorSelectionChanged(object sender, System.EventArgs e) { - SolutionItem ce = entrySelector.GetSelectedEntry (); + SolutionFolderItem ce = entrySelector.GetSelectedEntry (); if (ce != null) target.SetSolutionItem (ce, entrySelector.GetSelectedChildren ()); } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EntrySelectionTree.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EntrySelectionTree.cs index d5e531f3b8..662d2da34f 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EntrySelectionTree.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/EntrySelectionTree.cs @@ -7,6 +7,7 @@ using System.Collections.ObjectModel; using MonoDevelop.Ide; using MonoDevelop.Projects; using MonoDevelop.Components; +using System.Linq; namespace MonoDevelop.Deployment.Gui { @@ -15,7 +16,7 @@ namespace MonoDevelop.Deployment.Gui internal partial class EntrySelectionTree : Gtk.Bin { TreeStore store; - Dictionary<SolutionItem,SolutionItem> selectedEntries = new Dictionary<SolutionItem,SolutionItem> (); + Dictionary<SolutionFolderItem,SolutionFolderItem> selectedEntries = new Dictionary<SolutionFolderItem,SolutionFolderItem> (); PackageBuilder builder; Solution solution; @@ -44,13 +45,13 @@ namespace MonoDevelop.Deployment.Gui tree.AppendColumn (col); } - public void Fill (PackageBuilder builder, SolutionItem selection) + public void Fill (PackageBuilder builder, SolutionFolderItem selection) { store.Clear (); this.builder = builder; if (selection is SolutionFolder) { - foreach (SolutionItem e in ((SolutionFolder)selection).GetAllItems ()) { + foreach (SolutionFolderItem e in ((SolutionFolder)selection).GetAllItems ()) { if (builder.CanBuild (e)) selectedEntries [e] = e; } @@ -64,17 +65,15 @@ namespace MonoDevelop.Deployment.Gui else { solution = IdeApp.ProjectOperations.CurrentSelectedSolution; if (solution == null) { - ReadOnlyCollection<Solution> items = IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem.GetAllSolutions (); - if (items.Count > 0) - solution = items [0]; - else + solution = IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem.GetAllItems<Solution> ().FirstOrDefault(); + if (solution == null) return; } } AddEntry (TreeIter.Zero, solution.RootFolder); } - void AddEntry (TreeIter iter, SolutionItem entry) + void AddEntry (TreeIter iter, SolutionFolderItem entry) { string icon; if (entry.ParentFolder == null) @@ -101,49 +100,49 @@ namespace MonoDevelop.Deployment.Gui tree.ExpandToPath (store.GetPath (iter)); if (entry is SolutionFolder) { - foreach (SolutionItem ce in ((SolutionFolder)entry).Items) { + foreach (SolutionFolderItem ce in ((SolutionFolder)entry).Items) { AddEntry (iter, ce); } } } - public void SetSelection (SolutionItem rootEntry, SolutionItem[] childEntries) + public void SetSelection (SolutionFolderItem rootEntry, SolutionFolderItem[] childEntries) { selectedEntries.Clear (); selectedEntries [rootEntry] = rootEntry; - foreach (SolutionItem e in childEntries) + foreach (SolutionFolderItem e in childEntries) selectedEntries [e] = e; UpdateSelectionChecks (TreeIter.Zero, true); } - public SolutionItem GetSelectedEntry () + public SolutionFolderItem GetSelectedEntry () { return GetCommonSolutionItem (); } - public SolutionItem[] GetSelectedChildren () + public SolutionFolderItem[] GetSelectedChildren () { // The first entry is the root entry - SolutionItem common = GetCommonSolutionItem (); + SolutionFolderItem common = GetCommonSolutionItem (); if (common == null) return null; ArrayList list = new ArrayList (); - foreach (SolutionItem e in selectedEntries.Keys) + foreach (SolutionFolderItem e in selectedEntries.Keys) if (e != common) list.Add (e); - return (SolutionItem[]) list.ToArray (typeof(SolutionItem)); + return (SolutionFolderItem[]) list.ToArray (typeof(SolutionFolderItem)); } void OnToggled (object sender, Gtk.ToggledArgs args) { TreeIter iter; store.GetIterFromString (out iter, args.Path); - SolutionItem ob = (SolutionItem) store.GetValue (iter, 2); + SolutionFolderItem ob = (SolutionFolderItem) store.GetValue (iter, 2); if (selectedEntries.ContainsKey (ob)) { selectedEntries.Remove (ob); store.SetValue (iter, 3, false); if (ob is SolutionFolder) { - foreach (SolutionItem e in ((SolutionFolder)ob).GetAllItems ()) + foreach (SolutionFolderItem e in ((SolutionFolder)ob).GetAllItems ()) selectedEntries.Remove (e); UpdateSelectionChecks (TreeIter.Zero, false); } @@ -151,13 +150,13 @@ namespace MonoDevelop.Deployment.Gui selectedEntries [ob] = ob; store.SetValue (iter, 3, true); if (ob is SolutionFolder) { - foreach (SolutionItem e in ((SolutionFolder)ob).GetAllItems ()) { + foreach (SolutionFolderItem e in ((SolutionFolder)ob).GetAllItems ()) { if (builder.CanBuild (e)) selectedEntries [e] = e; } UpdateSelectionChecks (TreeIter.Zero, false); } - SelectCommonCombine ((SolutionItem)ob); + SelectCommonCombine ((SolutionFolderItem)ob); } if (SelectionChanged != null) SelectionChanged (this, EventArgs.Empty); @@ -174,7 +173,7 @@ namespace MonoDevelop.Deployment.Gui return; } do { - bool sel = selectedEntries.ContainsKey ((SolutionItem) store.GetValue (iter, 2)); + bool sel = selectedEntries.ContainsKey ((SolutionFolderItem) store.GetValue (iter, 2)); store.SetValue (iter, 3, sel); if (sel) tree.ExpandToPath (store.GetPath (iter)); @@ -183,16 +182,16 @@ namespace MonoDevelop.Deployment.Gui while (store.IterNext (ref iter)); } - void SelectCommonCombine (SolutionItem e) + void SelectCommonCombine (SolutionFolderItem e) { - SolutionItem common = GetCommonSolutionItem (); + SolutionFolderItem common = GetCommonSolutionItem (); if (common == null) return; selectedEntries [common] = common; - SolutionItem[] entries = new SolutionItem [selectedEntries.Count]; + SolutionFolderItem[] entries = new SolutionFolderItem [selectedEntries.Count]; selectedEntries.Keys.CopyTo (entries, 0); - foreach (SolutionItem se in entries) { - SolutionItem ce = se; + foreach (SolutionFolderItem se in entries) { + SolutionFolderItem ce = se; while (ce != null && ce != common) { selectedEntries [ce] = ce; ce = ce.ParentFolder; @@ -201,7 +200,7 @@ namespace MonoDevelop.Deployment.Gui UpdateSelectionChecks (TreeIter.Zero, false); } - SolutionItem GetCommonSolutionItem () + SolutionFolderItem GetCommonSolutionItem () { return PackageBuilder.GetCommonSolutionItem (selectedEntries.Keys); } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/InstallDialog.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/InstallDialog.cs index 921eab2bb2..e82e53a0d9 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/InstallDialog.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/InstallDialog.cs @@ -6,7 +6,7 @@ namespace MonoDevelop.Deployment.Gui { internal partial class InstallDialog : Gtk.Dialog { - public InstallDialog (SolutionItem entry) + public InstallDialog (SolutionFolderItem entry) { this.Build(); nameEntry.Text = entry.Name; diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeature.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeature.cs index d7ae6b1da2..823c8bf602 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeature.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeature.cs @@ -17,7 +17,7 @@ namespace MonoDevelop.Deployment.Gui get { return GettextCatalog.GetString ("Add a Packaging Project to the solution for generating different kinds of packages for the new project."); } } - public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionItem entry) + public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionFolderItem entry) { if (parentCombine == null) return FeatureSupportLevel.NotSupported; @@ -30,17 +30,17 @@ namespace MonoDevelop.Deployment.Gui return FeatureSupportLevel.NotSupported; } - public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionItem entry) + public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionFolderItem entry) { return new PackagingFeatureWidget (parentCombine, entry); } - public void ApplyFeature (SolutionFolder parentCombine, SolutionItem entry, Widget editor) + public void ApplyFeature (SolutionFolder parentCombine, SolutionFolderItem entry, Widget editor) { ((PackagingFeatureWidget)editor).ApplyFeature (); } - public string Validate (SolutionFolder parentCombine, SolutionItem entry, Gtk.Widget editor) + public string Validate (SolutionFolder parentCombine, SolutionFolderItem entry, Gtk.Widget editor) { return null; } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeatureWidget.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeatureWidget.cs index 75a45746c2..9f3b43045b 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeatureWidget.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Gui/PackagingFeatureWidget.cs @@ -4,6 +4,7 @@ using System.Collections; using System.Collections.ObjectModel; using MonoDevelop.Core; using MonoDevelop.Projects; +using System.Linq; namespace MonoDevelop.Deployment.Gui { @@ -11,22 +12,22 @@ namespace MonoDevelop.Deployment.Gui [System.ComponentModel.ToolboxItem(true)] internal partial class PackagingFeatureWidget : Gtk.Bin { - SolutionItem entry; + SolutionFolderItem entry; SolutionFolder parentFolder; ArrayList packages = new ArrayList (); PackagingProject newPackProject; bool creatingPackProject; - public PackagingFeatureWidget (SolutionFolder parentFolder, SolutionItem entry) + public PackagingFeatureWidget (SolutionFolder parentFolder, SolutionFolderItem entry) { this.Build(); this.entry = entry; this.parentFolder = parentFolder; - + creatingPackProject = entry is PackagingProject; if (!creatingPackProject) { - ReadOnlyCollection<PackagingProject> packProjects = parentFolder.ParentSolution.GetAllSolutionItems<PackagingProject> (); + var packProjects = parentFolder.ParentSolution.GetAllItems<PackagingProject> ().ToList (); newPackProject = new PackagingProject (); string label = GettextCatalog.GetString ("Create packages for this project in a new Packaging Project"); @@ -146,12 +147,12 @@ namespace MonoDevelop.Deployment.Gui if (creatingPackProject) { pb.SetSolutionItem (parentFolder.ParentSolution.RootFolder); // Add all compatible projects - foreach (SolutionItem e in parentFolder.ParentSolution.GetAllSolutionItems ()) { + foreach (SolutionFolderItem e in parentFolder.ParentSolution.GetAllSolutionItems ()) { if (pb.CanBuild (e)) pb.AddEntry (e); } } else { - pb.SetSolutionItem (parentFolder, new SolutionItem [] { entry }); + pb.SetSolutionItem (parentFolder, new SolutionFolderItem [] { entry }); } PackageBuilder[] defp = pb.CreateDefaultBuilders (); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.NodeBuilders/PackageNodeBuilder.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.NodeBuilders/PackageNodeBuilder.cs index 9ac26fb2c2..f721dfc27e 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.NodeBuilders/PackageNodeBuilder.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.NodeBuilders/PackageNodeBuilder.cs @@ -123,7 +123,7 @@ namespace MonoDevelop.Deployment.NodeBuilders Package package = CurrentNode.DataItem as Package; if (MessageService.AskQuestion (GettextCatalog.GetString ("Are you sure you want to delete the package '{0}'?", package.Name), AlertButton.Cancel, AlertButton.Delete) == AlertButton.Delete) { package.ParentProject.Packages.Remove (package); - IdeApp.ProjectOperations.Save (package.ParentProject); + IdeApp.ProjectOperations.SaveAsync (package.ParentProject); } } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BaseFuseFileCopyHandler.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BaseFuseFileCopyHandler.cs index b93a173858..dfaca87060 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BaseFuseFileCopyHandler.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BaseFuseFileCopyHandler.cs @@ -44,7 +44,7 @@ namespace MonoDevelop.Deployment.Targets get { throw new NotImplementedException ("Inheriting classes must override this."); } } - public override void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context) + public override void CopyFiles (ProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context) { DirectoryInfo tempDir = null; try { @@ -93,9 +93,9 @@ namespace MonoDevelop.Deployment.Targets tempDir.Delete (); } - public abstract void MountTempDirectory (IProgressMonitor monitor, FileCopyConfiguration copyConfig, string tempPath); + public abstract void MountTempDirectory (ProgressMonitor monitor, FileCopyConfiguration copyConfig, string tempPath); - protected void RunFuseCommand (IProgressMonitor monitor, string command, string args) + protected void RunFuseCommand (ProgressMonitor monitor, string command, string args) { LoggingService.LogInfo ("Running FUSE command: {0} {1}", command, args); var log = new StringWriter (); @@ -104,13 +104,12 @@ namespace MonoDevelop.Deployment.Targets RedirectStandardOutput = true, UseShellExecute = false, }; - using (var opMon = new AggregatedOperationMonitor (monitor)) { - using (var pWrapper = MonoDevelop.Core.Runtime.ProcessService.StartProcess (psi, log, log, null)) { - opMon.AddOperation (pWrapper); - pWrapper.WaitForOutput (); - if (pWrapper.ExitCode != 0) - throw new Exception (log.ToString ()); - } + + using (var pWrapper = Runtime.ProcessService.StartProcess (psi, log, log, null)) + using (monitor.CancellationToken.Register (pWrapper.Cancel)) { + pWrapper.WaitForOutput (); + if (pWrapper.ExitCode != 0) + throw new Exception (log.ToString ()); } } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BinariesZipPackageBuilder.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BinariesZipPackageBuilder.cs index b663c990b9..2149ea019b 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BinariesZipPackageBuilder.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/BinariesZipPackageBuilder.cs @@ -39,7 +39,7 @@ namespace MonoDevelop.Deployment.Targets get { return "Archive of Binaries"; } } - public override void InitializeSettings (SolutionItem entry) + public override void InitializeSettings (SolutionFolderItem entry) { targetFile = Path.Combine (entry.BaseDirectory, entry.Name) + ".tar.gz"; if (entry.ParentSolution != null) @@ -51,7 +51,7 @@ namespace MonoDevelop.Deployment.Targets return configuration != null ? new string [] { configuration } : new string [0]; } - public override bool CanBuild (SolutionItem entry) + public override bool CanBuild (SolutionFolderItem entry) { // Can build anything but PackagingProject return !(entry is PackagingProject); @@ -62,18 +62,21 @@ namespace MonoDevelop.Deployment.Targets return new DeployContext (this, platform, null); } - protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx) + protected override bool OnBuild (ProgressMonitor monitor, DeployContext ctx) { string tmpFolder = null; - + try { SolutionConfigurationSelector conf = (SolutionConfigurationSelector) configuration; - BuildResult res = RootSolutionItem.Build (monitor, conf); - if (res.ErrorCount > 0) { - foreach (BuildError e in res.Errors) - monitor.ReportError (e.ToString (), null); - monitor.ReportError (GettextCatalog.GetString ("The source project failed to build."), null); - return false; + var bt = RootSolutionItem as IBuildTarget; + if (bt != null) { + BuildResult res = bt.Build (monitor, conf).Result; + if (res.ErrorCount > 0) { + foreach (BuildError e in res.Errors) + monitor.ReportError (e.ToString (), null); + monitor.ReportError (GettextCatalog.GetString ("The source project failed to build."), null); + return false; + } } tmpFolder = FileService.CreateTempDirectory (); @@ -107,8 +110,7 @@ namespace MonoDevelop.Deployment.Targets if (tmpFolder != null) Directory.Delete (tmpFolder, true); } - if (monitor.AsyncOperation.Success) - monitor.Log.WriteLine (GettextCatalog.GetString ("Created file: {0}", targetFile)); + monitor.Log.WriteLine (GettextCatalog.GetString ("Created file: {0}", targetFile)); return true; } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/CommandPackageBuilder.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/CommandPackageBuilder.cs index 353331931a..a3d2a975c0 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/CommandPackageBuilder.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/CommandPackageBuilder.cs @@ -33,6 +33,7 @@ using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; using MonoDevelop.Core; using MonoDevelop.Core.Execution; +using System.Threading; namespace MonoDevelop.Deployment.Targets { @@ -88,7 +89,7 @@ namespace MonoDevelop.Deployment.Targets } } - protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx) + protected override bool OnBuild (ProgressMonitor monitor, DeployContext ctx) { string consMsg; IConsole cons; @@ -101,7 +102,7 @@ namespace MonoDevelop.Deployment.Targets } monitor.Log.WriteLine (GettextCatalog.GetString ("Executing: {0} {1} {2}", Command, Arguments, consMsg)); - IProcessAsyncOperation process = Runtime.ProcessService.StartConsoleProcess (Command, Arguments, workingDirectory, cons, null); + ProcessAsyncOperation process = Runtime.ProcessService.StartConsoleProcess (Command, Arguments, workingDirectory, cons, null); process.WaitForCompleted (); @@ -115,20 +116,21 @@ namespace MonoDevelop.Deployment.Targets class MonitorConsole: IConsole { StringReader nullReader; - IProgressMonitor monitor; + ProgressMonitor monitor; + CancellationTokenRegistration tr; - public MonitorConsole (IProgressMonitor monitor) + public MonitorConsole (ProgressMonitor monitor) { this.monitor = monitor; - monitor.CancelRequested += OnCancel; + tr = monitor.CancellationToken.Register (OnCancel); } public void Dispose () { - monitor.CancelRequested -= OnCancel; + tr.Dispose (); } - void OnCancel (IProgressMonitor monitor) + void OnCancel () { if (CancelRequested != null) CancelRequested (this, EventArgs.Empty); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/LocalFileCopyHandler.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/LocalFileCopyHandler.cs index f961d05edf..e143d62d39 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/LocalFileCopyHandler.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/LocalFileCopyHandler.cs @@ -51,12 +51,12 @@ namespace MonoDevelop.Deployment.Targets return new LocalFileCopyConfiguration (); } - public virtual void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context) + public virtual void CopyFiles (ProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context) { InternalCopyFiles (monitor, replacePolicy, copyConfig, deployFiles, context, null); } - internal void InternalCopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context, string realPrefix) + internal void InternalCopyFiles (ProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context, string realPrefix) { string targetDirectory = ((LocalFileCopyConfiguration) copyConfig).TargetDirectory; @@ -111,7 +111,7 @@ namespace MonoDevelop.Deployment.Targets long carry = 0; monitor.BeginTask (copyConfig.FriendlyLocation, progressBarLength); CopyReportCallback copyCallback = delegate (long bytes) { - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) return false; int steps = (int) (bytes / stepSize); carry += bytes % stepSize; @@ -127,7 +127,7 @@ namespace MonoDevelop.Deployment.Targets //now the actual copy foreach (DeployFileConf file in files) { //abort the copy if cancelling - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) break; EnsureDirectoryExists (Path.GetDirectoryName (file.InternalTargetFile)); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SourcesZipPackageBuilder.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SourcesZipPackageBuilder.cs index 83c06ffc2d..6820ae2d8f 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SourcesZipPackageBuilder.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SourcesZipPackageBuilder.cs @@ -24,9 +24,9 @@ namespace MonoDevelop.Deployment.Targets get { return "Archive of Sources"; } } - public override bool CanBuild (SolutionItem entry) + public override bool CanBuild (SolutionFolderItem entry) { - return entry is SolutionFolder || entry is SolutionEntityItem; + return entry is SolutionFolder || entry is SolutionItem; } @@ -58,14 +58,14 @@ namespace MonoDevelop.Deployment.Targets set { targetFile = value; } } - protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx) + protected override bool OnBuild (ProgressMonitor monitor, DeployContext ctx) { string sourceFile; - SolutionItem entry = RootSolutionItem; + SolutionFolderItem entry = RootSolutionItem; if (entry is SolutionFolder) sourceFile = entry.ParentSolution.FileName; else - sourceFile = ((SolutionEntityItem)entry).FileName; + sourceFile = ((SolutionItem)entry).FileName; AggregatedProgressMonitor mon = new AggregatedProgressMonitor (); mon.AddSlaveMonitor (monitor, MonitorAction.WriteLog|MonitorAction.ReportError|MonitorAction.ReportWarning|MonitorAction.ReportSuccess); @@ -81,13 +81,13 @@ namespace MonoDevelop.Deployment.Targets // Export the project - SolutionItem[] ents = GetChildEntries (); + SolutionFolderItem[] ents = GetChildEntries (); string[] epaths = new string [ents.Length]; for (int n=0; n<ents.Length; n++) epaths [n] = ents [n].ItemId; - Services.ProjectService.Export (mon, sourceFile, epaths, folder, FileFormat); - if (!mon.AsyncOperation.Success) + var r = Services.ProjectService.Export (mon, sourceFile, epaths, folder, FileFormat).Result; + if (string.IsNullOrEmpty (r)) return false; // Create the archive @@ -99,12 +99,11 @@ namespace MonoDevelop.Deployment.Targets finally { Directory.Delete (tmpFolder, true); } - if (monitor.AsyncOperation.Success) - monitor.Log.WriteLine (GettextCatalog.GetString ("Created file: {0}", targetFile)); + monitor.Log.WriteLine (GettextCatalog.GetString ("Created file: {0}", targetFile)); return true; } - public override void InitializeSettings (SolutionItem entry) + public override void InitializeSettings (SolutionFolderItem entry) { targetFile = Path.Combine (entry.BaseDirectory, entry.Name) + ".tar.gz"; if (entry.ParentSolution != null) diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SshFuseFileCopyHandler.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SshFuseFileCopyHandler.cs index fef148d5c1..4029434912 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SshFuseFileCopyHandler.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment.Targets/SshFuseFileCopyHandler.cs @@ -42,7 +42,7 @@ namespace MonoDevelop.Deployment.Targets get { return "SSH (FUSE)"; } } - public override void MountTempDirectory (IProgressMonitor monitor, FileCopyConfiguration copyConfig, string tempPath) + public override void MountTempDirectory (ProgressMonitor monitor, FileCopyConfiguration copyConfig, string tempPath) { SshFuseFileCopyConfiguration config = (SshFuseFileCopyConfiguration) copyConfig; string fuseArgs = string.Format ("{0} {1} {2}", config.TargetDirectory, tempPath, config.ExtraMountArguments); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DefaultDeployServiceExtension.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DefaultDeployServiceExtension.cs index 52715746d0..3b6554e7be 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DefaultDeployServiceExtension.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DefaultDeployServiceExtension.cs @@ -8,7 +8,7 @@ namespace MonoDevelop.Deployment { class DefaultDeployServiceExtension: DeployServiceExtension { - public override DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionItem entry, ConfigurationSelector configuration) + public override DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionFolderItem entry, ConfigurationSelector configuration) { if (entry is IDeployable) return new DeployFileCollection (((IDeployable)entry).GetDeployFiles (configuration)); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployFile.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployFile.cs index b8287104a5..e03eb8b89d 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployFile.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployFile.cs @@ -44,7 +44,7 @@ namespace MonoDevelop.Deployment string targetDirectoryID; DeployContext deployContext; bool isTemplate; - SolutionItem sourceSolutionItem; + SolutionFolderItem sourceSolutionItem; string displayName; DeployFileAttributes attributes; @@ -60,12 +60,12 @@ namespace MonoDevelop.Deployment sourceSolutionItem = pfile.Project; }
- public DeployFile (SolutionItem sourceSolutionItem, FilePath sourcePath, FilePath relativeTargetPath) + public DeployFile (SolutionFolderItem sourceSolutionItem, FilePath sourcePath, FilePath relativeTargetPath) : this (sourceSolutionItem, sourcePath, relativeTargetPath, TargetDirectory.ProgramFiles) { }
- public DeployFile (SolutionItem sourceSolutionItem, FilePath sourcePath, FilePath relativeTargetPath, string targetDirectoryID) + public DeployFile (SolutionFolderItem sourceSolutionItem, FilePath sourcePath, FilePath relativeTargetPath, string targetDirectoryID) { this.targetDirectoryID = targetDirectoryID; this.sourcePath = sourcePath; @@ -78,7 +78,7 @@ namespace MonoDevelop.Deployment this.deployContext = deployContext; } - public SolutionItem SourceSolutionItem { + public SolutionFolderItem SourceSolutionItem { get { return sourceSolutionItem; } } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployService.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployService.cs index b6f9695245..51fbdf8329 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployService.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployService.cs @@ -48,6 +48,7 @@ using ICSharpCode.SharpZipLib.Zip; using System.Reflection;
using Mono.Unix.Native;
using Mono.Unix; +using System.Threading.Tasks; namespace MonoDevelop.Deployment { @@ -90,7 +91,7 @@ namespace MonoDevelop.Deployment return props; } - public static PackageBuilder[] GetSupportedPackageBuilders (SolutionItem entry) + public static PackageBuilder[] GetSupportedPackageBuilders (SolutionFolderItem entry) { object[] builders = AddinManager.GetExtensionObjects ("/MonoDevelop/DeployService/PackageBuilders", false); ArrayList list = new ArrayList (); @@ -110,13 +111,13 @@ namespace MonoDevelop.Deployment return (PackageBuilder[]) AddinManager.GetExtensionObjects ("/MonoDevelop/DeployService/PackageBuilders", typeof(PackageBuilder), false); } - public static void Install (IProgressMonitor monitor, SolutionItem entry, string prefix, string appName, ConfigurationSelector configuration) + public static void Install (ProgressMonitor monitor, SolutionFolderItem entry, string prefix, string appName, ConfigurationSelector configuration) { InstallResolver res = new InstallResolver (); res.Install (monitor, entry, appName, prefix, configuration); } - public static void CreateArchive (IProgressMonitor mon, string folder, string targetFile) + public static void CreateArchive (ProgressMonitor mon, string folder, string targetFile) { string tf = Path.GetFileNameWithoutExtension (targetFile); if (tf.EndsWith (".tar")) tf = Path.GetFileNameWithoutExtension (tf); @@ -235,27 +236,29 @@ namespace MonoDevelop.Deployment return null; } - public static bool BuildPackage (IProgressMonitor mon, Package package) + public static Task<bool> BuildPackage (ProgressMonitor mon, Package package) { return BuildPackage (mon, package.PackageBuilder); } - public static bool BuildPackage (IProgressMonitor mon, PackageBuilder builder) + public static Task<bool> BuildPackage (ProgressMonitor mon, PackageBuilder builder) { - DeployServiceExtension extensionChain = GetExtensionChain (); - return extensionChain.BuildPackage (mon, builder); + return Task<bool>.Factory.StartNew (delegate { + DeployServiceExtension extensionChain = GetExtensionChain (); + return extensionChain.BuildPackage (mon, builder); + }); } - public static DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionItem[] entries, ConfigurationSelector configuration) + public static DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionFolderItem[] entries, ConfigurationSelector configuration) { DeployFileCollection col = new DeployFileCollection (); - foreach (SolutionItem e in entries) { + foreach (SolutionFolderItem e in entries) { col.AddRange (GetDeployFiles (ctx, e, configuration)); } return col; } - public static DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionItem entry, ConfigurationSelector configuration) + public static DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionFolderItem entry, ConfigurationSelector configuration) { ArrayList todel = new ArrayList (); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployServiceExtension.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployServiceExtension.cs index ef9335b420..4359230f6b 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployServiceExtension.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/DeployServiceExtension.cs @@ -9,7 +9,7 @@ namespace MonoDevelop.Deployment { internal DeployServiceExtension Next; - public virtual bool BuildPackage (IProgressMonitor monitor, PackageBuilder builder) + public virtual bool BuildPackage (ProgressMonitor monitor, PackageBuilder builder) { if (Next != null) return Next.BuildPackage (monitor, builder); @@ -17,7 +17,7 @@ namespace MonoDevelop.Deployment return builder.Build (monitor); } - public virtual DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionItem entry, ConfigurationSelector configuration) + public virtual DeployFileCollection GetDeployFiles (DeployContext ctx, SolutionFolderItem entry, ConfigurationSelector configuration) { if (entry is SolutionFolder) return GetCombineDeployFiles (ctx, (SolutionFolder) entry, configuration); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyConfiguration.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyConfiguration.cs index 0149d1040d..53c916d787 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyConfiguration.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyConfiguration.cs @@ -69,7 +69,7 @@ namespace MonoDevelop.Deployment get; } - public void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, DeployFileCollection files, DeployContext context) + public void CopyFiles (ProgressMonitor monitor, IFileReplacePolicy replacePolicy, DeployFileCollection files, DeployContext context) { Handler.CopyFiles (monitor, replacePolicy, this, files, context); } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyHandler.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyHandler.cs index 38108b7ded..7b1f3c2f00 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyHandler.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/FileCopyHandler.cs @@ -59,7 +59,7 @@ namespace MonoDevelop.Deployment return c; } - internal void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection files, DeployContext context) + internal void CopyFiles (ProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection files, DeployContext context) { handler.CopyFiles (monitor, replacePolicy, copyConfig, files, context); } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/IFileCopyHandler.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/IFileCopyHandler.cs index 58f41c36c7..1aabddc49e 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/IFileCopyHandler.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/IFileCopyHandler.cs @@ -40,6 +40,6 @@ namespace MonoDevelop.Deployment string Id { get; } string Name { get; } FileCopyConfiguration CreateConfiguration (); - void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection files, DeployContext context); + void CopyFiles (ProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection files, DeployContext context); } } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/InstallResolver.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/InstallResolver.cs index 50e1ca8951..778eb928ee 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/InstallResolver.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/InstallResolver.cs @@ -40,7 +40,7 @@ namespace MonoDevelop.Deployment { string appName; - public void Install (IProgressMonitor monitor, SolutionItem entry, string appName, string prefix, ConfigurationSelector configuration) + public void Install (ProgressMonitor monitor, SolutionFolderItem entry, string appName, string prefix, ConfigurationSelector configuration) { this.appName = appName; @@ -49,9 +49,9 @@ namespace MonoDevelop.Deployment } } - void InstallEntry (IProgressMonitor monitor, DeployContext ctx, SolutionItem entry, ConfigurationSelector configuration) + void InstallEntry (ProgressMonitor monitor, DeployContext ctx, SolutionFolderItem entry, ConfigurationSelector configuration) { - foreach (DeployFile df in DeployService.GetDeployFiles (ctx, new SolutionItem[] { entry }, configuration)) { + foreach (DeployFile df in DeployService.GetDeployFiles (ctx, new SolutionFolderItem[] { entry }, configuration)) { string targetPath = df.ResolvedTargetFile; if (targetPath == null) { monitor.ReportWarning ("Could not copy file '" + df.RelativeTargetPath + "': Unknown target directory."); @@ -64,7 +64,7 @@ namespace MonoDevelop.Deployment SolutionFolder c = entry as SolutionFolder; if (c != null) { monitor.BeginTask ("Installing solution '" + c.Name + "'", c.Items.Count); - foreach (SolutionItem ce in c.Items) { + foreach (SolutionFolderItem ce in c.Items) { InstallEntry (monitor, ctx, ce, configuration); monitor.Step (1); } @@ -72,7 +72,7 @@ namespace MonoDevelop.Deployment } } - void CopyFile (IProgressMonitor monitor, string src, string dest, DeployFileAttributes atts) + void CopyFile (ProgressMonitor monitor, string src, string dest, DeployFileAttributes atts) { dest = FileService.GetFullPath (dest); monitor.Log.WriteLine (GettextCatalog.GetString ("Deploying file {0}.", dest)); diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/Package.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/Package.cs index 8eeac21c76..22362fda36 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/Package.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/Package.cs @@ -6,6 +6,7 @@ using MonoDevelop.Core; using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; +using System.Threading.Tasks; namespace MonoDevelop.Deployment { @@ -46,11 +47,11 @@ namespace MonoDevelop.Deployment set { builder = value; NotifyChanged (); } } - public bool Build (IProgressMonitor monitor) + public async Task<bool> Build (ProgressMonitor monitor) { - DeployService.BuildPackage (monitor, this); + var res = await DeployService.BuildPackage (monitor, this); needsBuilding = false; - return true; + return res; } public bool NeedsBuilding { @@ -62,7 +63,7 @@ namespace MonoDevelop.Deployment } } - public void Clean (IProgressMonitor monitor) + public void Clean (ProgressMonitor monitor) { needsBuilding = true; } diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackageBuilder.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackageBuilder.cs index 3df5f51486..4dfa51c332 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackageBuilder.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackageBuilder.cs @@ -34,6 +34,7 @@ using MonoDevelop.Core; using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Projects; using MonoDevelop.Ide; +using System.Threading.Tasks; namespace MonoDevelop.Deployment { @@ -50,8 +51,8 @@ namespace MonoDevelop.Deployment [ItemProperty ("RootEntry")] SolutionItemReference rootEntry; - List<SolutionItem> childCombineEntries; - SolutionItem rootSolutionItem; + List<SolutionFolderItem> childCombineEntries; + SolutionFolderItem rootSolutionItem; public PackageBuilder () { @@ -76,7 +77,7 @@ namespace MonoDevelop.Deployment return null; } - internal bool Build (IProgressMonitor monitor) + internal bool Build (ProgressMonitor monitor) { monitor.BeginTask ("Package: " + Description, 1); DeployContext ctx = null; @@ -85,13 +86,11 @@ namespace MonoDevelop.Deployment if (ctx != null) ctx.FileFilter = this; if (!OnBuild (monitor, ctx)) { - monitor.AsyncOperation.Cancel (); return false; } } catch (Exception ex) { monitor.ReportError ("Package creation failed", ex); LoggingService.LogError ("Package creation failed", ex); - monitor.AsyncOperation.Cancel (); return false; } finally { monitor.EndTask (); @@ -101,12 +100,12 @@ namespace MonoDevelop.Deployment return true; } - public virtual bool CanBuild (SolutionItem entry) + public virtual bool CanBuild (SolutionFolderItem entry) { return true; } - public virtual void InitializeSettings (SolutionItem entry) + public virtual void InitializeSettings (SolutionFolderItem entry) { } @@ -123,7 +122,7 @@ namespace MonoDevelop.Deployment rootEntry = other.rootEntry; if (other.childCombineEntries != null) - childCombineEntries = new List<SolutionItem> (other.childCombineEntries); + childCombineEntries = new List<SolutionFolderItem> (other.childCombineEntries); else childCombineEntries = null; if (other.excludedFiles != null) @@ -138,7 +137,7 @@ namespace MonoDevelop.Deployment return new PackageBuilder [0]; } - protected virtual bool OnBuild (IProgressMonitor monitor, DeployContext ctx) + protected virtual bool OnBuild (ProgressMonitor monitor, DeployContext ctx) { return true; } @@ -158,15 +157,15 @@ namespace MonoDevelop.Deployment return new DeployContext (this, DeployService.CurrentPlatform, null); } - public void SetSolutionItem (SolutionItem entry) + public void SetSolutionItem (SolutionFolderItem entry) { SetSolutionItem (entry, null); } - public void SetSolutionItem (SolutionItem rootSolutionItem, IEnumerable<SolutionItem> childEntries) + public void SetSolutionItem (SolutionFolderItem rootSolutionItem, IEnumerable<SolutionFolderItem> childEntries) { this.rootSolutionItem = rootSolutionItem; - childCombineEntries = new List<SolutionItem> (); + childCombineEntries = new List<SolutionFolderItem> (); if (childEntries != null) childCombineEntries.AddRange (childEntries); @@ -187,11 +186,11 @@ namespace MonoDevelop.Deployment { this.rootEntry = new SolutionItemReference (rootSolutionItem); this.childEntries.Clear (); - foreach (SolutionItem e in childCombineEntries) + foreach (SolutionFolderItem e in childCombineEntries) childEntries.Add (new SolutionItemReference (e)); } - public SolutionItem RootSolutionItem { + public SolutionFolderItem RootSolutionItem { get { if (rootSolutionItem == null && rootEntry != null) rootSolutionItem = GetEntry (rootEntry); @@ -205,7 +204,7 @@ namespace MonoDevelop.Deployment } } - public void AddEntry (SolutionItem entry) + public void AddEntry (SolutionFolderItem entry) { SolutionItemReference fp = new SolutionItemReference (entry); foreach (SolutionItemReference s in childEntries) @@ -215,7 +214,7 @@ namespace MonoDevelop.Deployment if (rootEntry == fp) return; - List<SolutionItem> list = new List<SolutionItem> (); + List<SolutionFolderItem> list = new List<SolutionFolderItem> (); if (RootSolutionItem != null) list.Add (RootSolutionItem); list.AddRange (GetChildEntries()); @@ -224,8 +223,8 @@ namespace MonoDevelop.Deployment rootSolutionItem = GetCommonSolutionItem (list); list.Remove (rootSolutionItem); - foreach (SolutionItem e in list.ToArray ()) { - SolutionItem ce = e.ParentFolder; + foreach (SolutionFolderItem e in list.ToArray ()) { + SolutionFolderItem ce = e.ParentFolder; while (ce != rootSolutionItem) { if (!list.Contains (ce)) list.Add (ce); @@ -236,36 +235,36 @@ namespace MonoDevelop.Deployment UpdateEntryNames (); } - public SolutionItem[] GetChildEntries () + public SolutionFolderItem[] GetChildEntries () { if (childCombineEntries != null) return childCombineEntries.ToArray (); - childCombineEntries = new List<SolutionItem> (); + childCombineEntries = new List<SolutionFolderItem> (); foreach (SolutionItemReference en in childEntries) { - SolutionItem re = GetEntry (en); + SolutionFolderItem re = GetEntry (en); if (re != null && !(re is UnknownSolutionItem)) childCombineEntries.Add (re); } return childCombineEntries.ToArray (); } - public SolutionItem[] GetAllEntries () + public SolutionFolderItem[] GetAllEntries () { - List<SolutionItem> list = new List<SolutionItem> (); + List<SolutionFolderItem> list = new List<SolutionFolderItem> (); if (RootSolutionItem != null) list.Add (RootSolutionItem); list.AddRange (GetChildEntries ()); return list.ToArray (); } - SolutionItem GetEntry (SolutionItemReference reference) + SolutionFolderItem GetEntry (SolutionItemReference reference) { if (IdeApp.IsInitialized) - return Services.ProjectService.ReadSolutionItem (new NullProgressMonitor (), reference, IdeApp.Workspace.Items.ToArray ()); + return Services.ProjectService.ReadSolutionItem (new ProgressMonitor (), reference, IdeApp.Workspace.Items.ToArray ()).Result; else - return Services.ProjectService.ReadSolutionItem (new NullProgressMonitor (), reference); + return Services.ProjectService.ReadSolutionItem (new ProgressMonitor (), reference).Result; } public virtual DeployFileCollection GetDeployFiles (DeployContext ctx, ConfigurationSelector configuration) @@ -307,10 +306,10 @@ namespace MonoDevelop.Deployment } - internal static SolutionItem GetCommonSolutionItem (IEnumerable<SolutionItem> entries) + internal static SolutionFolderItem GetCommonSolutionItem (IEnumerable<SolutionFolderItem> entries) { - SolutionItem common = null; - foreach (SolutionItem it in entries) { + SolutionFolderItem common = null; + foreach (SolutionFolderItem it in entries) { if (common == null) common = it; else diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackagingProject.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackagingProject.cs index 184b2dee9f..6641fba97c 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackagingProject.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/PackagingProject.cs @@ -5,10 +5,11 @@ using System.Collections.Generic; using MonoDevelop.Core; using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; +using System.Threading.Tasks; namespace MonoDevelop.Deployment { - public class PackagingProject: SolutionEntityItem + public class PackagingProject: SolutionItem { PackageCollection packages; @@ -40,21 +41,19 @@ namespace MonoDevelop.Deployment return conf; } - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) { foreach (Package p in packages) p.Clean (monitor); + return Task.FromResult (BuildResult.Success); } - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected async override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { foreach (Package p in packages) - p.Build (monitor); - return null; - } - - protected override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) - { + if (!await p.Build (monitor)) + break; + return BuildResult.Success; } protected override bool OnGetNeedsBuilding (ConfigurationSelector configuration) @@ -65,12 +64,6 @@ namespace MonoDevelop.Deployment return false; } - protected override void OnSetNeedsBuilding (bool val, ConfigurationSelector configuration) - { - foreach (Package p in packages) - p.NeedsBuilding = val; - } - internal void NotifyPackagesChanged () { if (PackagesChanged != null) diff --git a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/UnknownPackageBuilder.cs b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/UnknownPackageBuilder.cs index 04d3e92770..72b356dc5d 100644 --- a/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/UnknownPackageBuilder.cs +++ b/main/src/addins/Deployment/MonoDevelop.Deployment/MonoDevelop.Deployment/UnknownPackageBuilder.cs @@ -54,7 +54,7 @@ namespace MonoDevelop.Deployment } } - protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx) + protected override bool OnBuild (ProgressMonitor monitor, DeployContext ctx) { monitor.ReportError ("Unknown package type. The package can't be generated.", null); return false; diff --git a/main/src/addins/GnomePlatform/GnomePlatform.cs b/main/src/addins/GnomePlatform/GnomePlatform.cs index beb5f8e4c0..556db7f7c9 100644 --- a/main/src/addins/GnomePlatform/GnomePlatform.cs +++ b/main/src/addins/GnomePlatform/GnomePlatform.cs @@ -208,7 +208,7 @@ namespace MonoDevelop.Platform TerminalRunnerHandler runner; TerminalOpenFolderRunnerHandler openDirectoryRunner; - public override IProcessAsyncOperation StartConsoleProcess (string command, string arguments, string workingDirectory, + public override ProcessAsyncOperation StartConsoleProcess (string command, string arguments, string workingDirectory, IDictionary<string, string> environmentVariables, string title, bool pauseWhenFinished) { diff --git a/main/src/addins/ILAsmBinding/ILAsmCompilerManager.cs b/main/src/addins/ILAsmBinding/ILAsmCompilerManager.cs index 1b334259ef..41da0dd356 100644 --- a/main/src/addins/ILAsmBinding/ILAsmCompilerManager.cs +++ b/main/src/addins/ILAsmBinding/ILAsmCompilerManager.cs @@ -48,7 +48,7 @@ namespace ILAsmBinding sb.Append ("\" "); } - public static BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) + public static BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor) { // ILAsmCompilerParameters compilerParameters = (ILAsmCompilerParameters)configuration.CompilationParameters ?? new ILAsmCompilerParameters (); string outputName = configuration.CompiledOutputName; diff --git a/main/src/addins/ILAsmBinding/ILAsmLanguageBinding.cs b/main/src/addins/ILAsmBinding/ILAsmLanguageBinding.cs index c45ea65c3f..ed2156ad5b 100644 --- a/main/src/addins/ILAsmBinding/ILAsmLanguageBinding.cs +++ b/main/src/addins/ILAsmBinding/ILAsmLanguageBinding.cs @@ -52,12 +52,12 @@ namespace ILAsmBinding return String.Compare (Path.GetExtension (fileName), ".il", StringComparison.OrdinalIgnoreCase) == 0; } - public BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) + public BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor) { return ILAsmCompilerManager.Compile (projectItems, configuration, configSelector, monitor); } - public ConfigurationParameters CreateCompilationParameters (XmlElement projectOptions) + public DotNetCompilerParameters CreateCompilationParameters (XmlElement projectOptions) { return new ILAsmCompilerParameters(); } diff --git a/main/src/addins/ILAsmBinding/Project/ILAsmCompilerParameters.cs b/main/src/addins/ILAsmBinding/Project/ILAsmCompilerParameters.cs index 80c1af76db..9b509a6112 100644 --- a/main/src/addins/ILAsmBinding/Project/ILAsmCompilerParameters.cs +++ b/main/src/addins/ILAsmBinding/Project/ILAsmCompilerParameters.cs @@ -26,7 +26,7 @@ namespace ILAsmBinding { - class ILAsmCompilerParameters : MonoDevelop.Projects.ConfigurationParameters + class ILAsmCompilerParameters : MonoDevelop.Projects.DotNetCompilerParameters { } } diff --git a/main/src/addins/MacPlatform/Dialogs/SelectEncodingPopUpButton.cs b/main/src/addins/MacPlatform/Dialogs/SelectEncodingPopUpButton.cs index 02ffe31e1a..5483cbbd78 100644 --- a/main/src/addins/MacPlatform/Dialogs/SelectEncodingPopUpButton.cs +++ b/main/src/addins/MacPlatform/Dialogs/SelectEncodingPopUpButton.cs @@ -25,12 +25,14 @@ // THE SOFTWARE. using System; +using System.Linq; using Foundation; using AppKit; using MonoDevelop.Core; using MonoDevelop.Ide; using MonoDevelop.Projects.Text; +using System.Linq; namespace MonoDevelop.MacIntegration { @@ -94,9 +96,7 @@ namespace MonoDevelop.MacIntegration if (clear) Menu.RemoveAllItems (); - encodings = SelectedEncodings.ConversionEncodings; - if (encodings == null || encodings.Length == 0) - encodings = SelectedEncodings.DefaultEncodings; + encodings = TextEncoding.ConversionEncodings.Select ((e) => e.CodePage).ToArray (); if (autoDetectedItem != null) { Menu.AddItem (autoDetectedItem); diff --git a/main/src/addins/MacPlatform/MacExternalConsoleProcess.cs b/main/src/addins/MacPlatform/MacExternalConsoleProcess.cs index dcafe4127f..b92f968216 100644 --- a/main/src/addins/MacPlatform/MacExternalConsoleProcess.cs +++ b/main/src/addins/MacPlatform/MacExternalConsoleProcess.cs @@ -36,7 +36,7 @@ using MonoDevelop.MacInterop; namespace MonoDevelop.MacIntegration { - internal class MacExternalConsoleProcess : IProcessAsyncOperation + internal class MacExternalConsoleProcess : ProcessAsyncOperation { /* NOTES ON CONTROLLING A TERMINAL WITH APPLESCRIPT @@ -80,11 +80,16 @@ bash pause on exit trick */ string tabId, windowId; bool cancelled; - + public MacExternalConsoleProcess (string command, string arguments, string workingDirectory, IDictionary<string, string> environmentVariables, string title, bool pauseWhenFinished) { + CancellationTokenSource = new CancellationTokenSource (); + CancellationTokenSource.Token.Register (CloseTerminal); + + // FIXME set value of ExitCode and ProcessId, if possible + RunTerminal ( command, arguments, workingDirectory, environmentVariables, title, pauseWhenFinished, out tabId, out windowId @@ -168,67 +173,15 @@ end tell", tabId, windowId); #endregion - #region IProcessAsyncOperation implementation - - public void Dispose () - { - } - - public int ExitCode { - get { - //FIXME: implement. is it possible? - return 0; - } - } - - public int ProcessId { - get { - //FIXME: implement. is it possible? - return 0; - } - } - - #endregion - #region IAsyncOperation implementation - public event OperationHandler Completed; - - public void Cancel () + void CloseTerminal () { cancelled = true; //FIXME: try to kill the process without closing the window, if pauseWhenFinished is true CloseTerminalWindow (tabId, windowId); } - - public void WaitForCompleted () - { - while (!IsCompleted) { - Thread.Sleep (1000); - } - } - - public bool IsCompleted { - get { - //FIXME: get the status of the process, not the whole script - return !TabExists (tabId, windowId); - } - } - - public bool Success { - get { - //FIXME: any way to get the real result? - return !cancelled; - } - } - - - public bool SuccessWithWarnings { - get { - return Success; - } - } - + #endregion } }
\ No newline at end of file diff --git a/main/src/addins/MacPlatform/MacMenu/MDMenuItem.cs b/main/src/addins/MacPlatform/MacMenu/MDMenuItem.cs index 2040fd91d4..84585c1f40 100644 --- a/main/src/addins/MacPlatform/MacMenu/MDMenuItem.cs +++ b/main/src/addins/MacPlatform/MacMenu/MDMenuItem.cs @@ -155,6 +155,8 @@ namespace MonoDevelop.MacIntegration.MacMenu void SetItemValues (NSMenuItem item, CommandInfo info, bool disabledVisible) { item.SetTitleWithMnemonic (GetCleanCommandText (info)); + if (!string.IsNullOrEmpty (info.Description) && item.ToolTip != info.Description) + item.ToolTip = info.Description; bool enabled = info.Enabled && (!IsGloballyDisabled || commandSource == CommandSource.ContextMenu); bool visible = info.Visible && (disabledVisible || info.Enabled); diff --git a/main/src/addins/MacPlatform/MacPlatform.cs b/main/src/addins/MacPlatform/MacPlatform.cs index 11eb1419ad..c8625333fa 100644 --- a/main/src/addins/MacPlatform/MacPlatform.cs +++ b/main/src/addins/MacPlatform/MacPlatform.cs @@ -349,7 +349,7 @@ namespace MonoDevelop.MacIntegration if (!Int32.TryParse (qs ["column"], out column)) column = 1; - return new FileOpenInformation (fileUri.AbsolutePath, + return new FileOpenInformation (Uri.UnescapeDataString(fileUri.AbsolutePath), line, column, OpenDocumentOptions.DefaultInternal); } catch (Exception ex) { LoggingService.LogError ("Invalid TextMate URI: " + url, ex); @@ -519,7 +519,7 @@ namespace MonoDevelop.MacIntegration return res != null ? res.ToXwtImage () : base.OnGetIconForFile (filename); } - public override IProcessAsyncOperation StartConsoleProcess (string command, string arguments, string workingDirectory, + public override ProcessAsyncOperation StartConsoleProcess (string command, string arguments, string workingDirectory, IDictionary<string, string> environmentVariables, string title, bool pauseWhenFinished) { @@ -736,5 +736,42 @@ namespace MonoDevelop.MacIntegration return toplevels.Any (t => t.Key.IsVisible && (t.Value == null || t.Value.Modal) && !t.Key.DebugDescription.StartsWith ("<NSStatusBarWindow", StringComparison.Ordinal)); } + + public override void AddChildWindow (Gtk.Window parent, Gtk.Window child) + { + NSWindow w = GtkQuartz.GetWindow (parent); + child.Realize (); + NSWindow overlay = GtkQuartz.GetWindow (child); + overlay.SetExcludedFromWindowsMenu (true); + w.AddChildWindow (overlay, NSWindowOrderingMode.Above); + } + + public override void PlaceWindow (Gtk.Window window, int x, int y, int width, int height) + { + NSWindow w = GtkQuartz.GetWindow (window); + var dr = FromDesktopRect (new Gdk.Rectangle (x, y, width, height)); + var r = w.FrameRectFor (dr); + w.SetFrame (r, true); + base.PlaceWindow (window, x, y, width, height); + } + + static CGRect FromDesktopRect (Gdk.Rectangle r) + { + var desktopBounds = CalcDesktopBounds (); + r.Y = desktopBounds.Height - r.Y - r.Height; + if (desktopBounds.Y < 0) + r.Y += desktopBounds.Y; + return new CGRect (desktopBounds.X + r.X, r.Y, r.Width, r.Height); + } + + static Gdk.Rectangle CalcDesktopBounds () + { + var desktopBounds = new Gdk.Rectangle (); + foreach (var s in NSScreen.Screens) { + var r = s.Frame; + desktopBounds = desktopBounds.Union (new Gdk.Rectangle ((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height)); + } + return desktopBounds; + } } } diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyBrowserWidget.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyBrowserWidget.cs index 52cd6144e7..0483763f79 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyBrowserWidget.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyBrowserWidget.cs @@ -158,10 +158,10 @@ namespace MonoDevelop.AssemblyBrowser }; languageCombobox = Gtk.ComboBox.NewText (); - //languageCombobox.AppendText (GettextCatalog.GetString ("Summary")); + languageCombobox.AppendText (GettextCatalog.GetString ("Summary")); languageCombobox.AppendText (GettextCatalog.GetString ("IL")); languageCombobox.AppendText (GettextCatalog.GetString ("C#")); - languageCombobox.Active = Math.Min (1, PropertyService.Get ("AssemblyBrowser.InspectLanguage", 1)); + languageCombobox.Active = Math.Min (0, PropertyService.Get ("AssemblyBrowser.Language", 0)); languageCombobox.Changed += LanguageComboboxhandleChanged; loader = new CecilLoader (true); @@ -338,7 +338,7 @@ namespace MonoDevelop.AssemblyBrowser void LanguageComboboxhandleChanged (object sender, EventArgs e) { this.notebook1.Page = 0; - PropertyService.Set ("AssemblyBrowser.InspectLanguage", this.languageCombobox.Active); + PropertyService.Set ("AssemblyBrowser.Language", this.languageCombobox.Active); FillInspectLabel (); } @@ -1112,10 +1112,15 @@ namespace MonoDevelop.AssemblyBrowser switch (this.languageCombobox.Active) { case 0: inspectEditor.Options.ShowFoldMargin = true; + this.inspectEditor.Document.MimeType = "text/x-csharp"; + SetReferencedSegments (builder.GetSummary (inspectEditor.GetTextEditorData (), nav, PublicApiOnly)); + break; + case 1: + inspectEditor.Options.ShowFoldMargin = true; this.inspectEditor.Document.MimeType = "text/x-ilasm"; SetReferencedSegments (builder.Disassemble (inspectEditor.GetTextEditorData (), nav)); break; - case 1: + case 2: inspectEditor.Options.ShowFoldMargin = true; this.inspectEditor.Document.MimeType = "text/x-csharp"; SetReferencedSegments (builder.Decompile (inspectEditor.GetTextEditorData (), nav, PublicApiOnly)); @@ -1188,10 +1193,14 @@ namespace MonoDevelop.AssemblyBrowser return; if (nav != null) return; - if (currentAssembly != null) { - OpenFromAssembly (url, currentAssembly); - } else { - OpenFromAssemblyNames (url); + try { + if (currentAssembly != null) { + OpenFromAssembly (url, currentAssembly); + } else { + OpenFromAssemblyNames (url); + } + } catch (Exception e) { + LoggingService.LogError ("Error while opening the assembly browser with id:" + url, e); } } @@ -1220,20 +1229,22 @@ namespace MonoDevelop.AssemblyBrowser t2.Wait (); if (definitions == null) // disposed return; - var nav = SearchMember (url); - if (nav == null) { - if (++i == references.Count) - LoggingService.LogError ("Assembly browser: Can't find: " + url + "."); - else - loadNext (); - } + Application.Invoke (delegate { + var nav = SearchMember (url); + if (nav == null) { + if (++i == references.Count) + LoggingService.LogError ("Assembly browser: Can't find: " + url + "."); + else + loadNext (); + } + }); }, TaskScheduler.Current); }; } void OpenFromAssemblyNames (string url) { - List<Task> tasks = new List<Task> (); + var tasks = new List<Task> (); foreach (var definition in definitions.ToArray ()) { var cecilObject = loader.GetCecilObject (definition.UnresolvedAssembly); if (cecilObject == null) { @@ -1259,14 +1270,22 @@ namespace MonoDevelop.AssemblyBrowser Task.Factory.ContinueWhenAll (tasks.ToArray (), tarr => { var exceptions = tarr.Where (t => t.IsFaulted).Select (t => t.Exception).ToArray (); if (exceptions != null) { - throw new AggregateException (exceptions).Flatten (); + var ex = new AggregateException (exceptions).Flatten (); + if (ex.InnerExceptions.Count > 0) { + foreach (var inner in ex.InnerExceptions) { + LoggingService.LogError ("Error while loading assembly in the browser.", inner); + } + throw ex; + } } if (definitions == null) // disposed return; - var nav = SearchMember (url); - if (nav == null) { - LoggingService.LogError ("Assembly browser: Can't find: " + url + "."); - } + Application.Invoke (delegate { + var nav = SearchMember (url); + if (nav == null) { + LoggingService.LogError ("Assembly browser: Can't find: " + url + "."); + } + }); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current); } @@ -1437,13 +1456,17 @@ namespace MonoDevelop.AssemblyBrowser Application.Invoke (delegate { if (definitions == null) return; - ITreeBuilder builder; - if (definitions.Count + projects.Count == 1) { - builder = TreeView.LoadTree (result); - } else { - builder = TreeView.AddChild (result); + try { + ITreeBuilder builder; + if (definitions.Count + projects.Count == 1) { + builder = TreeView.LoadTree (result); + } else { + builder = TreeView.AddChild (result); + } + builder.Selected = builder.Expanded = selectReference; + } catch (Exception e) { + LoggingService.LogError ("Error while adding assembly to the assembly list", e); } - builder.Selected = builder.Expanded = selectReference; }); } ); diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyLoader.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyLoader.cs index c23bc5fc3f..71ebaa6b72 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyLoader.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/AssemblyLoader.cs @@ -75,9 +75,14 @@ namespace MonoDevelop.AssemblyBrowser if (!File.Exists (fileName)) throw new ArgumentException ("File doesn't exist.", "fileName"); this.assemblyLoaderTask = Task.Factory.StartNew<AssemblyDefinition> (() => { - return AssemblyDefinition.ReadAssembly (FileName, new ReaderParameters () { - AssemblyResolver = this - }); + try { + return AssemblyDefinition.ReadAssembly (FileName, new ReaderParameters { + AssemblyResolver = this + }); + } catch (Exception e) { + LoggingService.LogError ("Error while reading assembly " + FileName, e); + return null; + } }, src.Token); this.unresolvedAssembly = new Lazy<IUnresolvedAssembly> (delegate { diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/IAssemblyBrowserNodeBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/IAssemblyBrowserNodeBuilder.cs index 27529ebaa7..7a13a020b6 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/IAssemblyBrowserNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/IAssemblyBrowserNodeBuilder.cs @@ -39,5 +39,6 @@ namespace MonoDevelop.AssemblyBrowser string GetDocumentationMarkup (ITreeNavigator navigator); List<ReferenceSegment> Disassemble (TextEditorData data, ITreeNavigator navigator); List<ReferenceSegment> Decompile (TextEditorData data, ITreeNavigator navigator, bool publicOnly); + List<ReferenceSegment> GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly); } } diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/AssemblyNodeBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/AssemblyNodeBuilder.cs index 6d9d6f7bc5..a9dd6a68ba 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/AssemblyNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/AssemblyNodeBuilder.cs @@ -176,7 +176,21 @@ namespace MonoDevelop.AssemblyBrowser b.AddAssembly (compilationUnit, true); }); } - + + List<ReferenceSegment> IAssemblyBrowserNodeBuilder.GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly) + { + var assembly = ((AssemblyLoader)navigator.DataItem).UnresolvedAssembly; + var compilationUnit = Widget.CecilLoader.GetCecilObject (assembly); + if (compilationUnit == null) { + LoggingService.LogError ("Can't get cecil object for assembly:" + assembly); + return new List<ReferenceSegment> (); + } + return DomMethodNodeBuilder.GetSummary (data, DomMethodNodeBuilder.GetModule (navigator), null, b => { + if (b != null) + b.AddAssembly (compilationUnit, true); + }); + } + public string GetDocumentationMarkup (ITreeNavigator navigator) { return null; diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomEventNodeBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomEventNodeBuilder.cs index abccf4c5f8..d04c119022 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomEventNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomEventNodeBuilder.cs @@ -105,7 +105,15 @@ namespace MonoDevelop.AssemblyBrowser var evt = CecilLoader.GetCecilObject ((IUnresolvedEvent)navigator.DataItem); return DomMethodNodeBuilder.Decompile (data, DomMethodNodeBuilder.GetModule (navigator), evt.DeclaringType, b => b.AddEvent (evt)); } - + + List<ReferenceSegment> IAssemblyBrowserNodeBuilder.GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly) + { + if (DomMethodNodeBuilder.HandleSourceCodeEntity (navigator, data)) + return null; + var evt = CecilLoader.GetCecilObject ((IUnresolvedEvent)navigator.DataItem); + return DomMethodNodeBuilder.GetSummary (data, DomMethodNodeBuilder.GetModule (navigator), evt.DeclaringType, b => b.AddEvent (evt)); + } + string IAssemblyBrowserNodeBuilder.GetDocumentationMarkup (ITreeNavigator navigator) { var evt = (IUnresolvedEvent)navigator.DataItem; diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomFieldNodeBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomFieldNodeBuilder.cs index 8206ac909b..f56ad572f6 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomFieldNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomFieldNodeBuilder.cs @@ -92,7 +92,15 @@ namespace MonoDevelop.AssemblyBrowser var field = CecilLoader.GetCecilObject ((IUnresolvedField)navigator.DataItem); return DomMethodNodeBuilder.Decompile (data, DomMethodNodeBuilder.GetModule (navigator), field.DeclaringType, b => b.AddField (field)); } - + + List<ReferenceSegment> IAssemblyBrowserNodeBuilder.GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly) + { + if (DomMethodNodeBuilder.HandleSourceCodeEntity (navigator, data)) + return null; + var field = CecilLoader.GetCecilObject ((IUnresolvedField)navigator.DataItem); + return DomMethodNodeBuilder.GetSummary (data, DomMethodNodeBuilder.GetModule (navigator), field.DeclaringType, b => b.AddField (field)); + } + string IAssemblyBrowserNodeBuilder.GetDocumentationMarkup (ITreeNavigator navigator) { var field = (IUnresolvedField)navigator.DataItem; diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomMethodNodeBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomMethodNodeBuilder.cs index fd4b4afdd8..1a9b29e791 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomMethodNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomMethodNodeBuilder.cs @@ -130,20 +130,58 @@ namespace MonoDevelop.AssemblyBrowser public static List<ReferenceSegment> Decompile (TextEditorData data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData, DecompilerSettings settings) { + var context = new DecompilerContext (module); + var source = new CancellationTokenSource (); + context.CancellationToken = source.Token; + context.CurrentType = currentType; + context.Settings = settings; try { + var astBuilder = new AstBuilder (context); + setData (astBuilder); + astBuilder.RunTransformations (o => false); + GeneratedCodeSettings.Default.Apply (astBuilder.SyntaxTree); + var output = new ColoredCSharpFormatter (data.Document); + astBuilder.GenerateCode (output); + output.SetDocumentData (); + return output.ReferencedSegments; + } catch (Exception e) { + // exception -> try to decompile without method bodies + try { + var astBuilder = new AstBuilder (context); + astBuilder.DecompileMethodBodies = false; + setData (astBuilder); + astBuilder.RunTransformations (o => false); + GeneratedCodeSettings.Default.Apply (astBuilder.SyntaxTree); + var output = new ColoredCSharpFormatter (data.Document); + astBuilder.GenerateCode (output); + output.SetDocumentData (); + data.Document.Insert (data.Document.TextLength, "/* body decompilation failed: \n" + e + " */"); + } catch (Exception e2) { + data.Text = "/* fallback decompilation failed: \n" + e2 +"*/"; + } + } + return null; + } - var context = new DecompilerContext (module); - var source = new CancellationTokenSource (); - - context.CancellationToken = source.Token; - context.CurrentType = currentType; - - context.Settings = settings; - - AstBuilder astBuilder = new AstBuilder (context); - + public static List<ReferenceSegment> GetSummary (TextEditorData data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData) + { + var types = DesktopService.GetMimeTypeInheritanceChain (data.Document.MimeType); + var codePolicy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types); + var settings = DomTypeNodeBuilder.CreateDecompilerSettings (false, codePolicy); + return GetSummary (data, module, currentType, setData, settings); + } + + public static List<ReferenceSegment> GetSummary (TextEditorData data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData, DecompilerSettings settings) + { + var context = new DecompilerContext (module); + var source = new CancellationTokenSource (); + context.CancellationToken = source.Token; + context.CurrentType = currentType; + context.Settings = settings; + try { + var astBuilder = new AstBuilder (context); + astBuilder.DecompileMethodBodies = false; setData (astBuilder); - astBuilder.RunTransformations (o => false); GeneratedCodeSettings.Default.Apply (astBuilder.SyntaxTree); var output = new ColoredCSharpFormatter (data.Document); @@ -151,11 +189,11 @@ namespace MonoDevelop.AssemblyBrowser output.SetDocumentData (); return output.ReferencedSegments; } catch (Exception e) { - data.Text = "Decompilation failed: \n" + e; + data.Text = "/* decompilation failed: \n" + e +"*/"; } return null; } - + internal static string GetAttributes (Ambience ambience, IEnumerable<IAttribute> attributes) { StringBuilder result = new StringBuilder (); @@ -180,6 +218,17 @@ namespace MonoDevelop.AssemblyBrowser return DomMethodNodeBuilder.Decompile (data, DomMethodNodeBuilder.GetModule (navigator), cecilMethod.DeclaringType, b => b.AddMethod (cecilMethod)); } + List<ReferenceSegment> IAssemblyBrowserNodeBuilder.GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly) + { + var method = (IUnresolvedMethod)navigator.DataItem; + if (HandleSourceCodeEntity (navigator, data)) + return null; + var cecilMethod = CecilLoader.GetCecilObject (method); + if (cecilMethod == null) + return null; + return DomMethodNodeBuilder.GetSummary (data, DomMethodNodeBuilder.GetModule (navigator), cecilMethod.DeclaringType, b => b.AddMethod (cecilMethod)); + } + static void AppendLink (StringBuilder sb, string link, string text) { sb.Append ("<span style=\"text.link\"><u><a ref=\""); diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomPropertyNodeBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomPropertyNodeBuilder.cs index 01e7d3b412..465b41300b 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomPropertyNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomPropertyNodeBuilder.cs @@ -115,6 +115,14 @@ namespace MonoDevelop.AssemblyBrowser return DomMethodNodeBuilder.Decompile (data, DomMethodNodeBuilder.GetModule (navigator), property.DeclaringType, b => b.AddProperty (property)); } + List<ReferenceSegment> IAssemblyBrowserNodeBuilder.GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly) + { + if (DomMethodNodeBuilder.HandleSourceCodeEntity (navigator, data)) + return null; + var property = CecilLoader.GetCecilObject ((IUnresolvedProperty)navigator.DataItem); + return DomMethodNodeBuilder.GetSummary (data, DomMethodNodeBuilder.GetModule (navigator), property.DeclaringType, b => b.AddProperty (property)); + } + string IAssemblyBrowserNodeBuilder.GetDocumentationMarkup (ITreeNavigator navigator) { var property = (IUnresolvedProperty)navigator.DataItem; diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomTypeNodeBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomTypeNodeBuilder.cs index 07568c4f9f..35ba03ed84 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomTypeNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/DomTypeNodeBuilder.cs @@ -212,7 +212,23 @@ namespace MonoDevelop.AssemblyBrowser builder.AddType (type); }, settings); } - + + List<ReferenceSegment> IAssemblyBrowserNodeBuilder.GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly) + { + if (DomMethodNodeBuilder.HandleSourceCodeEntity (navigator, data)) + return null; + var type = CecilLoader.GetCecilObject ((IUnresolvedTypeDefinition)navigator.DataItem); + if (type == null) + return null; + var types = DesktopService.GetMimeTypeInheritanceChain (data.Document.MimeType); + var codePolicy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types); + var settings = CreateDecompilerSettings (publicOnly, codePolicy); + return DomMethodNodeBuilder.GetSummary (data, DomMethodNodeBuilder.GetModule (navigator), type, builder => { + builder.AddType (type); + }, settings); + } + + string IAssemblyBrowserNodeBuilder.GetDocumentationMarkup (ITreeNavigator navigator) { var type = (IUnresolvedTypeDefinition)navigator.DataItem; diff --git a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/NamespaceBuilder.cs b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/NamespaceBuilder.cs index 4073b4de9a..e19351f894 100644 --- a/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/NamespaceBuilder.cs +++ b/main/src/addins/MonoDevelop.AssemblyBrowser/MonoDevelop.AssemblyBrowser/TreeNodes/NamespaceBuilder.cs @@ -111,6 +111,12 @@ namespace MonoDevelop.AssemblyBrowser { return Disassemble (data, navigator); } + + List<ReferenceSegment> IAssemblyBrowserNodeBuilder.GetSummary (TextEditorData data, ITreeNavigator navigator, bool publicOnly) + { + return Disassemble (data, navigator); + } + string IAssemblyBrowserNodeBuilder.GetDocumentationMarkup (ITreeNavigator navigator) { return null; diff --git a/main/src/addins/MonoDevelop.Autotools/AutotoolsContext.cs b/main/src/addins/MonoDevelop.Autotools/AutotoolsContext.cs index 2b5465c414..99b3f1d937 100644 --- a/main/src/addins/MonoDevelop.Autotools/AutotoolsContext.cs +++ b/main/src/addins/MonoDevelop.Autotools/AutotoolsContext.cs @@ -45,7 +45,7 @@ namespace MonoDevelop.Autotools Set<SystemPackage> commonPackages; Set<string> globalFilesReferences = new Set<string>(); Set<string> compilers = new Set<string> (); - Set<SolutionItem> builtProjects = new Set<SolutionItem> (); + Set<SolutionFolderItem> builtProjects = new Set<SolutionFolderItem> (); // Useful for cleaning up in case of a problem in generation List<string> generatedFiles = new List<string> (); @@ -190,12 +190,12 @@ namespace MonoDevelop.Autotools globalFilesReferences.Add (filePath); } - public void RegisterBuiltProject (SolutionItem item) + public void RegisterBuiltProject (SolutionFolderItem item) { builtProjects.Add (item); } - public IEnumerable<SolutionItem> GetBuiltProjects () + public IEnumerable<SolutionFolderItem> GetBuiltProjects () { return builtProjects; } @@ -292,7 +292,7 @@ namespace MonoDevelop.Autotools // TODO: add an extension point with which addins can implement // autotools functionality. - public static IMakefileHandler GetMakefileHandler (SolutionItem entry, MakefileType mt) + public static IMakefileHandler GetMakefileHandler (SolutionFolderItem entry, MakefileType mt) { foreach (IMakefileHandler mh in AddinManager.GetExtensionObjects ("/MonoDevelop/Autotools/MakefileHandlers", typeof(IMakefileHandler), true)) { if (mh.CanDeploy (entry, mt)) diff --git a/main/src/addins/MonoDevelop.Autotools/Commands.cs b/main/src/addins/MonoDevelop.Autotools/Commands.cs index d3954156ae..d553c16ac0 100644 --- a/main/src/addins/MonoDevelop.Autotools/Commands.cs +++ b/main/src/addins/MonoDevelop.Autotools/Commands.cs @@ -39,7 +39,7 @@ namespace MonoDevelop.Autotools { public override bool CanBuildNode (Type dataType) { - return typeof (Solution).IsAssignableFrom (dataType) || typeof (SolutionItem).IsAssignableFrom (dataType); + return typeof (Solution).IsAssignableFrom (dataType) || typeof (SolutionFolderItem).IsAssignableFrom (dataType); } public override Type CommandHandlerType { @@ -52,25 +52,25 @@ namespace MonoDevelop.Autotools [CommandHandler (Commands.GenerateFiles)] protected void OnGenerate() { - SolutionItem entry = CurrentNode.DataItem as SolutionItem; + SolutionFolderItem entry = CurrentNode.DataItem as SolutionFolderItem; Solution solution = CurrentNode.DataItem as Solution; GenerateMakefiles (entry, solution); } - internal static void GenerateMakefiles (SolutionItem entry, Solution solution) + internal static void GenerateMakefiles (SolutionFolderItem entry, Solution solution) { if (solution == null) { AlertButton generateMakefilesButton = new AlertButton (GettextCatalog.GetString ("_Generate Makefiles")); if (MessageService.AskQuestion (GettextCatalog.GetString ("Generating Makefiles is not supported for single projects. Do you want to generate them for the full solution - '{0}' ?", entry.ParentSolution.Name), AlertButton.Cancel, generateMakefilesButton) == generateMakefilesButton) - solution = ((SolutionItem)entry).ParentSolution; + solution = ((SolutionFolderItem)entry).ParentSolution; else return; } DeployContext ctx = null; - IProgressMonitor monitor = null; + ProgressMonitor monitor = null; GenerateMakefilesDialog dialog = new GenerateMakefilesDialog (solution); try { diff --git a/main/src/addins/MonoDevelop.Autotools/FileNodeBuilderExtension.cs b/main/src/addins/MonoDevelop.Autotools/FileNodeBuilderExtension.cs index c586f3681e..1c90564ec3 100644 --- a/main/src/addins/MonoDevelop.Autotools/FileNodeBuilderExtension.cs +++ b/main/src/addins/MonoDevelop.Autotools/FileNodeBuilderExtension.cs @@ -44,7 +44,7 @@ namespace MonoDevelop.Autotools } } - Set<SolutionEntityItem> projects = new Set<SolutionEntityItem> (); + Set<SolutionItem> projects = new Set<SolutionItem> (); foreach (ITreeNavigator node in CurrentNodes) { ProjectFile file = (ProjectFile) node.DataItem; @@ -57,7 +57,7 @@ namespace MonoDevelop.Autotools } } - IdeApp.ProjectOperations.Save (projects); + IdeApp.ProjectOperations.SaveAsync (projects); } [CommandUpdateHandler (Commands.SynchWithMakefile)] diff --git a/main/src/addins/MonoDevelop.Autotools/Handler.cs b/main/src/addins/MonoDevelop.Autotools/Handler.cs index ccf029a7bd..a8622a6c59 100644 --- a/main/src/addins/MonoDevelop.Autotools/Handler.cs +++ b/main/src/addins/MonoDevelop.Autotools/Handler.cs @@ -76,18 +76,18 @@ namespace MonoDevelop.Autotools set { defaultConfig = value; } } - public override bool CanBuild (SolutionItem entry) + public override bool CanBuild (SolutionFolderItem entry) { SolutionDeployer deployer = new SolutionDeployer (generateAutotools); return deployer.CanDeploy ( entry ); } - public override void InitializeSettings (SolutionItem entry) + public override void InitializeSettings (SolutionFolderItem entry) { if (string.IsNullOrEmpty (targetDir)) targetDir = entry.BaseDirectory; if (string.IsNullOrEmpty (defaultConfig)) { - SolutionEntityItem se = entry as SolutionEntityItem; + SolutionItem se = entry as SolutionItem; defaultConfig = se != null ? se.GetConfigurations () [0] : null; } if (File.Exists (Path.Combine (entry.BaseDirectory, "autogen.sh")) || @@ -99,18 +99,18 @@ namespace MonoDevelop.Autotools } - protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx) + protected override bool OnBuild (ProgressMonitor monitor, DeployContext ctx) { string tmpFolder = FileService.CreateTempDirectory (); Solution solution = null; - SolutionItem entry = RootSolutionItem; + SolutionFolderItem entry = RootSolutionItem; try { if (generateFiles) { List<string> childEntries = new List<string> (); if (entry is SolutionFolder) { - SolutionItem[] ents = GetChildEntries (); - foreach (SolutionItem it in ents) + SolutionFolderItem[] ents = GetChildEntries (); + foreach (SolutionFolderItem it in ents) childEntries.Add (it.ItemId); } else { @@ -123,22 +123,21 @@ namespace MonoDevelop.Autotools if (entry is SolutionFolder) sourceFile = entry.ParentSolution.FileName; else - sourceFile = ((SolutionEntityItem)entry).FileName; + sourceFile = ((SolutionItem)entry).FileName; - string efile = Services.ProjectService.Export (new FilteredProgressMonitor (monitor), sourceFile, childEntries.ToArray (), tmpFolder, null); + string efile = Services.ProjectService.Export (new FilteredProgressMonitor (monitor), sourceFile, childEntries.ToArray (), tmpFolder, null).Result; if (efile == null) { monitor.ReportError (GettextCatalog.GetString ("The project could not be exported."), null); return false; } - solution = Services.ProjectService.ReadWorkspaceItem (new NullProgressMonitor (), efile) as Solution; + solution = Services.ProjectService.ReadWorkspaceItem (new ProgressMonitor (), efile).Result as Solution; } else { solution = entry.ParentSolution; } - solution.Build (monitor, (SolutionConfigurationSelector) defaultConfig); - - if (monitor.IsCancelRequested || !monitor.AsyncOperation.Success) + var res = solution.Build (monitor, (SolutionConfigurationSelector) defaultConfig).Result; + if (res.HasErrors || monitor.CancellationToken.IsCancellationRequested) return false; SolutionDeployer deployer = new SolutionDeployer (generateAutotools); diff --git a/main/src/addins/MonoDevelop.Autotools/IMakefileHandler.cs b/main/src/addins/MonoDevelop.Autotools/IMakefileHandler.cs index ac4a8ed108..31c6b18ccc 100644 --- a/main/src/addins/MonoDevelop.Autotools/IMakefileHandler.cs +++ b/main/src/addins/MonoDevelop.Autotools/IMakefileHandler.cs @@ -29,9 +29,9 @@ namespace MonoDevelop.Autotools { public interface IMakefileHandler { - bool CanDeploy (SolutionItem entry, MakefileType type); + bool CanDeploy (SolutionFolderItem entry, MakefileType type); - Makefile Deploy (AutotoolsContext ctx, SolutionItem entry, IProgressMonitor monitor); + Makefile Deploy (AutotoolsContext ctx, SolutionFolderItem entry, ProgressMonitor monitor); } public enum MakefileType diff --git a/main/src/addins/MonoDevelop.Autotools/MakefileData.cs b/main/src/addins/MonoDevelop.Autotools/MakefileData.cs index 8101bcfe67..01a6b1cb51 100644 --- a/main/src/addins/MonoDevelop.Autotools/MakefileData.cs +++ b/main/src/addins/MonoDevelop.Autotools/MakefileData.cs @@ -38,6 +38,7 @@ using MonoDevelop.Core.Serialization; using MonoDevelop.Projects; using MonoDevelop.Core.Assemblies; using MonoDevelop.Ide; +using System.Xml; namespace MonoDevelop.Autotools { @@ -70,6 +71,24 @@ namespace MonoDevelop.Autotools if (assemblyContext == null) integrationEnabled = false; } + + public static MakefileData Read (XmlElement ext) + { + XmlDataSerializer ser = new XmlDataSerializer (new DataContext ()); + return (MakefileData) ser.Deserialize (new XmlNodeReader (ext), typeof(MakefileData)); + } + + public XmlElement Write () + { + XmlDataSerializer ser = new XmlDataSerializer (new DataContext ()); + var sw = new StringWriter (); + ser.Serialize (new XmlTextWriter (sw), this); + XmlDocument doc = new XmlDocument (); + doc.LoadXml (sw.ToString ()); + var elem = doc.DocumentElement; + doc.RemoveChild (elem); + return elem; + } internal static IAssemblyContext GetMonoRuntimeContext () { @@ -613,7 +632,7 @@ namespace MonoDevelop.Autotools return customRegex [index]; } - IProgressMonitor monitor = null; + ProgressMonitor monitor = null; // VarName -> Encode filenames Eg. $(srcdir) Dictionary<string, bool> encodeValues; @@ -651,7 +670,7 @@ namespace MonoDevelop.Autotools } //use events.. - public void UpdateProject (IProgressMonitor monitor, bool promptForRemoval) + public void UpdateProject (ProgressMonitor monitor, bool promptForRemoval) { if (!IntegrationEnabled) return; @@ -1177,7 +1196,7 @@ namespace MonoDevelop.Autotools return pref; } - public static void ResolveProjectReferences (SolutionFolder folder, IProgressMonitor monitor) + public static void ResolveProjectReferences (SolutionFolder folder, ProgressMonitor monitor) { Dictionary<string, DotNetProject> projects = new Dictionary<string, DotNetProject> (); foreach (DotNetProject p in folder.GetAllItems<DotNetProject> ()) { @@ -1325,7 +1344,7 @@ namespace MonoDevelop.Autotools //Writing methods - public void UpdateMakefile (IProgressMonitor monitor) + public void UpdateMakefile (ProgressMonitor monitor) { //FIXME: AssemblyName & OutputDir diff --git a/main/src/addins/MonoDevelop.Autotools/MakefileGeneratorTool.cs b/main/src/addins/MonoDevelop.Autotools/MakefileGeneratorTool.cs index 8c483aff93..76af27790c 100644 --- a/main/src/addins/MonoDevelop.Autotools/MakefileGeneratorTool.cs +++ b/main/src/addins/MonoDevelop.Autotools/MakefileGeneratorTool.cs @@ -50,7 +50,7 @@ namespace MonoDevelop.Autotools Console.WriteLine (GettextCatalog.GetString ("Loading solution file {0}", filename)); ConsoleProgressMonitor monitor = new ConsoleProgressMonitor (); - Solution solution = Services.ProjectService.ReadWorkspaceItem (monitor, filename) as Solution; + Solution solution = Services.ProjectService.ReadWorkspaceItem (monitor, filename).Result as Solution; if (solution == null) { Console.WriteLine (GettextCatalog.GetString ("Error: Makefile generation supported only for solutions.\n")); return 1; diff --git a/main/src/addins/MonoDevelop.Autotools/MakefileIntegrationFeature.cs b/main/src/addins/MonoDevelop.Autotools/MakefileIntegrationFeature.cs index 8c08e1dc0f..df3511903f 100644 --- a/main/src/addins/MonoDevelop.Autotools/MakefileIntegrationFeature.cs +++ b/main/src/addins/MonoDevelop.Autotools/MakefileIntegrationFeature.cs @@ -17,7 +17,7 @@ namespace MonoDevelop.Autotools get { return string.Empty; } } - public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionItem entry) + public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionFolderItem entry) { if (entry is Project) return FeatureSupportLevel.SupportedByDefault; @@ -25,17 +25,17 @@ namespace MonoDevelop.Autotools return FeatureSupportLevel.NotSupported; } - public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionItem entry) + public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionFolderItem entry) { return new MakefileIntegrationFeatureWidget ((Project)entry); } - public void ApplyFeature (SolutionFolder parentCombine, SolutionItem entry, Widget editor) + public void ApplyFeature (SolutionFolder parentCombine, SolutionFolderItem entry, Widget editor) { ((MakefileIntegrationFeatureWidget)editor).Store (); } - public string Validate (SolutionFolder parentCombine, SolutionItem entry, Gtk.Widget editor) + public string Validate (SolutionFolder parentCombine, SolutionFolderItem entry, Gtk.Widget editor) { return null; } diff --git a/main/src/addins/MonoDevelop.Autotools/MakefileOptionPanelWidget.cs b/main/src/addins/MonoDevelop.Autotools/MakefileOptionPanelWidget.cs index c003789327..447b16994e 100644 --- a/main/src/addins/MonoDevelop.Autotools/MakefileOptionPanelWidget.cs +++ b/main/src/addins/MonoDevelop.Autotools/MakefileOptionPanelWidget.cs @@ -268,7 +268,7 @@ namespace MonoDevelop.Autotools //FIXME: Do this only if there are changes b/w tmpData and Data project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] = tmpData; - using (IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor ( + using (ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor ( GettextCatalog.GetString ("Updating project"), "gtk-run", true)) { tmpData.UpdateProject (monitor, oldData == null || (!oldData.IntegrationEnabled && tmpData.IntegrationEnabled)); diff --git a/main/src/addins/MonoDevelop.Autotools/MakefileProject.cs b/main/src/addins/MonoDevelop.Autotools/MakefileProject.cs index 91dd984bd9..23a9125a6c 100644 --- a/main/src/addins/MonoDevelop.Autotools/MakefileProject.cs +++ b/main/src/addins/MonoDevelop.Autotools/MakefileProject.cs @@ -17,10 +17,10 @@ namespace MonoDevelop.Autotools conf.Name = name; return conf; } - - public override IEnumerable<string> GetProjectTypes () + + protected override void OnGetProjectTypes (HashSet<string> types) { - yield return "MakefileProject"; + types.Add ("MakefileProject"); } } diff --git a/main/src/addins/MonoDevelop.Autotools/MakefileProjectServiceExtension.cs b/main/src/addins/MonoDevelop.Autotools/MakefileProjectServiceExtension.cs index 5c71be9a49..1ca531fbaa 100644 --- a/main/src/addins/MonoDevelop.Autotools/MakefileProjectServiceExtension.cs +++ b/main/src/addins/MonoDevelop.Autotools/MakefileProjectServiceExtension.cs @@ -38,15 +38,17 @@ using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; +using System.Linq; +using System.Threading.Tasks; namespace MonoDevelop.Autotools { public class MakefileProjectServiceExtension : ProjectServiceExtension { - public override WorkspaceItem LoadWorkspaceItem (IProgressMonitor monitor, string fileName) + public async override Task<WorkspaceItem> LoadWorkspaceItem (ProgressMonitor monitor, string fileName) { - WorkspaceItem item = base.LoadWorkspaceItem (monitor, fileName); - + WorkspaceItem item = await base.LoadWorkspaceItem (monitor, fileName); + Solution sol = item as Solution; if (sol != null) { //Resolve project references @@ -59,68 +61,65 @@ namespace MonoDevelop.Autotools "Error resolving Makefile based project references for solution {0}", sol.Name), e); } } - + return item; } + } - - protected override SolutionEntityItem LoadSolutionItem (IProgressMonitor monitor, string fileName) + [RegisterProjectModelExtension] + public class MakefileProjectExtension: ProjectExtension + { + MakefileData data; + + protected override void OnReadProject (ProgressMonitor monitor, MonoDevelop.Projects.Formats.MSBuild.MSBuildProject msproject) { - SolutionEntityItem entry = base.LoadSolutionItem (monitor, fileName); - if (entry == null) - return null; - - Project project = entry as Project; - if (project == null) - return entry; + base.OnReadProject (monitor, msproject); + var ext = msproject.GetMonoDevelopProjectExtension ("MonoDevelop.Autotools.MakefileInfo"); + if (ext == null) + return; - //Project - MakefileData data = entry.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData; + data = MakefileData.Read (ext); if (data == null) - return entry; + return; monitor.BeginTask (GettextCatalog.GetString ("Updating project from Makefile"), 1); try { - data.OwnerProject = project;
+ data.OwnerProject = Project; if (data.SupportsIntegration) data.UpdateProject (monitor, false); monitor.Step (1); } catch (Exception e) { monitor.ReportError (GettextCatalog.GetString ( - "Error loading Makefile for project {0}", project.Name), e); + "\tError loading Makefile for project {0}", Project.Name), e); } finally { monitor.EndTask (); } - return entry; } - public override void Save (IProgressMonitor monitor, SolutionEntityItem entry) + protected override void OnWriteProject (ProgressMonitor monitor, MonoDevelop.Projects.Formats.MSBuild.MSBuildProject msproject) { - base.Save (monitor, entry); - - Project project = entry as Project; - if (project == null) - return; - - MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
+ base.OnWriteProject (monitor, msproject); + if (data == null || !data.SupportsIntegration) return; + msproject.SetProjectExtension ("MonoDevelop.Autotools.MakefileInfo", data.Write ()); + try { data.UpdateMakefile (monitor); } catch (Exception e) { LoggingService.LogError (GettextCatalog.GetString ("Error saving to Makefile ({0}) for project {1}", - data.AbsoluteMakefileName, project.Name, e)); + data.AbsoluteMakefileName, Project.Name, e)); monitor.ReportError (GettextCatalog.GetString ( - "Error saving to Makefile ({0}) for project {1}", data.AbsoluteMakefileName, project.Name), e); + "Error saving to Makefile ({0}) for project {1}", data.AbsoluteMakefileName, Project.Name), e); } }
- public override List<FilePath> GetItemFiles (SolutionEntityItem entry, bool includeReferencedFiles) + protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) {
- List<FilePath> col = base.GetItemFiles (entry, includeReferencedFiles); + List<FilePath> col = base.OnGetItemFiles (includeReferencedFiles).ToList (); - MakefileData data = entry.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
+ MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
if (data == null || !data.SupportsIntegration || string.IsNullOrEmpty (data.AbsoluteMakefileName)) return col; @@ -136,31 +135,21 @@ namespace MonoDevelop.Autotools } - //TODO - protected override bool GetNeedsBuilding (SolutionEntityItem entry, ConfigurationSelector configuration) - { - return base.GetNeedsBuilding (entry, configuration); - } - //FIXME: Check whether autogen.sh is required or not - protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) + protected async override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { - Project project = entry as Project; - if (project == null) - return base.Build (monitor, entry, configuration); - - MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
+ MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.BuildTargetName)) - return base.Build (monitor, entry, configuration); + return await base.OnBuild (monitor, configuration); //FIXME: Gen autofoo ? autoreconf? string output = String.Empty; int exitCode = 0; - monitor.BeginTask (GettextCatalog.GetString ("Building {0}", project.Name), 1); + monitor.BeginTask (GettextCatalog.GetString ("Building {0}", Project.Name), 1); try { - string baseDir = project.BaseDirectory; + string baseDir = Project.BaseDirectory; string args = string.Format ("-j {0} {1}", data.ParallelProcesses, data.BuildTargetName); using (var swOutput = new StringWriter ()) { @@ -174,7 +163,8 @@ namespace MonoDevelop.Autotools chainedOutput, chainedOutput, null)) { - process.WaitForOutput (); + + await process.Task; chainedOutput.UnchainWriter (monitor.Log); chainedOutput.UnchainWriter (swOutput); @@ -200,7 +190,7 @@ namespace MonoDevelop.Autotools Regex regexError = data.GetErrorRegex (false); Regex regexWarning = data.GetWarningRegex (false); - BuildResult cr = ParseOutput (tf, output, project.BaseDirectory, regexError, regexWarning); + BuildResult cr = ParseOutput (tf, output, Project.BaseDirectory, regexError, regexWarning); if (exitCode != 0 && cr.FailedBuildCount == 0) cr.AddError (GettextCatalog.GetString ("Build failed. See Build Output panel.")); @@ -330,24 +320,17 @@ namespace MonoDevelop.Autotools return null; } - protected override void Clean (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) + protected async override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) { - Project proj = entry as Project; - if (proj == null) { - base.Clean (monitor, entry, configuration); - return; - } - - MakefileData data = proj.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
+ MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.CleanTargetName)) { - base.Clean (monitor, entry, configuration); - return; + return await base.OnClean (monitor, configuration); } monitor.BeginTask ( GettextCatalog.GetString( "Cleaning project"), 1); try { - string baseDir = proj.BaseDirectory; + string baseDir = Project.BaseDirectory; ProcessWrapper process = Runtime.ProcessService.StartProcess ( "make", data.CleanTargetName, @@ -355,7 +338,8 @@ namespace MonoDevelop.Autotools monitor.Log, monitor.Log, null ); - process.WaitForOutput (); + + await process.Task; if ( process.ExitCode > 0 ) throw new Exception ( GettextCatalog.GetString ("An unspecified error occurred while running '{0}'", "make " + data.CleanTargetName) ); @@ -365,52 +349,47 @@ namespace MonoDevelop.Autotools catch ( Exception e ) { monitor.ReportError ( GettextCatalog.GetString ("Project could not be cleaned: "), e ); - return; + var res = new BuildResult (); + res.AddError (GettextCatalog.GetString ("Project could not be cleaned: ") + e.Message); + return res; } finally { monitor.EndTask (); } monitor.ReportSuccess ( GettextCatalog.GetString ( "Project successfully cleaned")); + return BuildResult.Success; } - protected override bool CanExecute (SolutionEntityItem item, ExecutionContext context, ConfigurationSelector configuration) + protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) { - Project project = item as Project; - if (project != null) { - MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
- if (data != null && data.SupportsIntegration && !String.IsNullOrEmpty (data.ExecuteTargetName)) - return true; - } - return base.CanExecute (item, context, configuration); + MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
+ if (data != null && data.SupportsIntegration && !String.IsNullOrEmpty (data.ExecuteTargetName)) + return true; + return base.OnGetCanExecute (context, configuration); } - protected override void Execute (IProgressMonitor monitor, SolutionEntityItem entry, ExecutionContext context, ConfigurationSelector configuration) + protected async override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { - Project project = entry as Project; - if (project == null) { - base.Execute (monitor, entry, context, configuration); - return; - } - - MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
+ MakefileData data = Project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.ExecuteTargetName)) { - base.Execute (monitor, entry, context, configuration); + base.OnExecute (monitor, context, configuration); return; } IConsole console = context.ConsoleFactory.CreateConsole (true); - monitor.BeginTask (GettextCatalog.GetString ("Executing {0}", project.Name), 1); + monitor.BeginTask (GettextCatalog.GetString ("Executing {0}", Project.Name), 1); try { ProcessWrapper process = Runtime.ProcessService.StartProcess ("make", - data.ExecuteTargetName, - project.BaseDirectory, - console.Out, - console.Error, - null); - process.WaitForOutput (); + data.ExecuteTargetName, + Project.BaseDirectory, + console.Out, + console.Error, + null); + + await process.Task; monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", process.ExitCode)); monitor.Step (1); diff --git a/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.addin.xml b/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.addin.xml index 0ed738152b..2388eb28f7 100644 --- a/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.addin.xml +++ b/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.addin.xml @@ -29,6 +29,12 @@ </Condition> </Extension> + <Extension path = "/MonoDevelop/ProjectModel/ProjectModelExtensions"> + <Condition id="Platform" value="!windows"> + <ProjectExtension class = "MonoDevelop.Autotools.MakefileProjectExtension" id="MakefileProjectServiceExtension" insertafter="FinalStep"/> + </Condition> + </Extension> + <Extension path = "/MonoDevelop/Ide/Commands"> <Condition id="Platform" value="!windows"> <Category _name = "Autotools" id = "Autotools"> diff --git a/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.csproj b/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.csproj index 47387c921d..84c712ed90 100644 --- a/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.csproj +++ b/main/src/addins/MonoDevelop.Autotools/MonoDevelop.Autotools.csproj @@ -85,6 +85,7 @@ <Reference Include="glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> <SpecificVersion>False</SpecificVersion> </Reference> + <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="AssemblyInfo.cs" /> diff --git a/main/src/addins/MonoDevelop.Autotools/SimpleProjectMakefileHandler.cs b/main/src/addins/MonoDevelop.Autotools/SimpleProjectMakefileHandler.cs index 6f4d39496f..b3bc53e342 100644 --- a/main/src/addins/MonoDevelop.Autotools/SimpleProjectMakefileHandler.cs +++ b/main/src/addins/MonoDevelop.Autotools/SimpleProjectMakefileHandler.cs @@ -71,7 +71,7 @@ namespace MonoDevelop.Autotools // store all refs for easy access Set<SystemPackage> pkgs; - public bool CanDeploy (SolutionItem entry, MakefileType type) + public bool CanDeploy (SolutionFolderItem entry, MakefileType type) { Project project = entry as Project; if ( project == null ) return false; @@ -89,7 +89,7 @@ namespace MonoDevelop.Autotools return null; } - public Makefile Deploy (AutotoolsContext ctx, SolutionItem entry, IProgressMonitor monitor) + public Makefile Deploy (AutotoolsContext ctx, SolutionFolderItem entry, ProgressMonitor monitor) { generateAutotools = ctx.MakefileType == MakefileType.AutotoolsMakefile; @@ -324,7 +324,7 @@ namespace MonoDevelop.Autotools ctx.AddBuiltFile (Path.Combine (config.OutputDirectory, bfile)); DeployFileCollection deployFiles = DeployService.GetDeployFiles ( - ctx.DeployContext, new SolutionItem[] { project }, config.Selector); + ctx.DeployContext, new SolutionFolderItem[] { project }, config.Selector); ProcessDeployFilesForConfig (deployFiles, project, configSection, ctx, config); configSections.Add (configSection); @@ -677,7 +677,7 @@ endif", s.SwitchName.Replace ('-', '_').ToUpperInvariant (), s.Define)); return dir; } - void EmitCustomCommandTargets (CustomCommandCollection commands, Project project, StringBuilder builder, string configName, CustomCommandType[] types, IProgressMonitor monitor) + void EmitCustomCommandTargets (CustomCommandCollection commands, Project project, StringBuilder builder, string configName, CustomCommandType[] types, ProgressMonitor monitor) { bool warned = false; configName = configName.ToUpper (); @@ -735,7 +735,7 @@ endif", s.SwitchName.Replace ('-', '_').ToUpperInvariant (), s.Define)); } // Get the Project config corresponding to its @parentConfig - internal static SolutionItemConfiguration GetProjectConfig (string parentConfig, SolutionEntityItem entry, out bool enabled) + internal static SolutionItemConfiguration GetProjectConfig (string parentConfig, SolutionItem entry, out bool enabled) { enabled = false; SolutionConfiguration solutionConfig = entry.ParentSolution.Configurations [parentConfig] as SolutionConfiguration; diff --git a/main/src/addins/MonoDevelop.Autotools/SolutionDeployer.cs b/main/src/addins/MonoDevelop.Autotools/SolutionDeployer.cs index 3bb43a271b..16d1bd6081 100644 --- a/main/src/addins/MonoDevelop.Autotools/SolutionDeployer.cs +++ b/main/src/addins/MonoDevelop.Autotools/SolutionDeployer.cs @@ -71,14 +71,14 @@ namespace MonoDevelop.Autotools } } - public bool CanDeploy (SolutionItem entry) + public bool CanDeploy (SolutionFolderItem entry) { MakefileType mt = generateAutotools ? MakefileType.AutotoolsMakefile : MakefileType.SimpleMakefile; IMakefileHandler handler = AutotoolsContext.GetMakefileHandler (entry, mt); return handler != null; } - public bool GenerateFiles (DeployContext ctx, Solution solution, string defaultConf, IProgressMonitor monitor ) + public bool GenerateFiles (DeployContext ctx, Solution solution, string defaultConf, ProgressMonitor monitor ) { string filesString = generateAutotools ? "Autotools files" : "Makefiles"; monitor.BeginTask ( GettextCatalog.GetString ("Generating {0} for Solution {1}", filesString, solution.Name), 1 ); @@ -153,7 +153,7 @@ namespace MonoDevelop.Autotools return true; } - public bool Deploy ( DeployContext ctx, Solution solution, string defaultConf, string targetDir, bool generateFiles, IProgressMonitor monitor ) + public bool Deploy ( DeployContext ctx, Solution solution, string defaultConf, string targetDir, bool generateFiles, ProgressMonitor monitor ) { if (generateFiles) { if ( !GenerateFiles ( ctx, solution, defaultConf, monitor ) ) @@ -231,7 +231,7 @@ namespace MonoDevelop.Autotools if ( File.Exists ( file ) ) FileService.DeleteFile ( file ); } - void AddTopLevelMakefileVars ( Makefile makefile, IProgressMonitor monitor) + void AddTopLevelMakefileVars ( Makefile makefile, ProgressMonitor monitor) { monitor.Log.WriteLine ( GettextCatalog.GetString ("Adding variables to top-level Makefile") ); @@ -251,7 +251,7 @@ namespace MonoDevelop.Autotools // makefile.AppendToVariable ( "pkglib_DATA", "$(DLL_REFERENCES)" ); } - void CreateAutoGenDotSH (AutotoolsContext context, IProgressMonitor monitor) + void CreateAutoGenDotSH (AutotoolsContext context, ProgressMonitor monitor) { monitor.Log.WriteLine ( GettextCatalog.GetString ("Creating autogen.sh") ); @@ -278,7 +278,7 @@ namespace MonoDevelop.Autotools Syscall.chmod ( fileName , FilePermissions.S_IXOTH | FilePermissions.S_IROTH | FilePermissions.S_IRWXU | FilePermissions.S_IRWXG ); } - void CreateConfigureDotAC (Solution solution, string defaultConf, IProgressMonitor monitor, AutotoolsContext context) + void CreateConfigureDotAC (Solution solution, string defaultConf, ProgressMonitor monitor, AutotoolsContext context) { monitor.Log.WriteLine ( GettextCatalog.GetString ("Creating configure.ac") ); TemplateEngine templateEngine = new TemplateEngine(); @@ -394,7 +394,7 @@ AM_CONDITIONAL(ENABLE_{3}, test x$enable_{2} = xyes)", context.AddGeneratedFile (configureFileName); } - void CreateConfigureScript (Solution solution, string defaultConf, AutotoolsContext ctx, IProgressMonitor monitor) + void CreateConfigureScript (Solution solution, string defaultConf, AutotoolsContext ctx, ProgressMonitor monitor) { monitor.Log.WriteLine ( GettextCatalog.GetString ("Creating configure script") ); @@ -469,7 +469,7 @@ AM_CONDITIONAL(ENABLE_{3}, test x$enable_{2} = xyes)", return builder.ToString (); } - void CreateMakefileInclude (AutotoolsContext context, IProgressMonitor monitor) + void CreateMakefileInclude (AutotoolsContext context, ProgressMonitor monitor) { monitor.Log.WriteLine ( GettextCatalog.GetString ("Creating Makefile.include") ); diff --git a/main/src/addins/MonoDevelop.Autotools/SolutionMakefileHandler.cs b/main/src/addins/MonoDevelop.Autotools/SolutionMakefileHandler.cs index b31e5ddba0..ab70a6472d 100644 --- a/main/src/addins/MonoDevelop.Autotools/SolutionMakefileHandler.cs +++ b/main/src/addins/MonoDevelop.Autotools/SolutionMakefileHandler.cs @@ -33,12 +33,12 @@ namespace MonoDevelop.Autotools bool generateAutotools = true; // Recurses into children and tests if they are deployable. - public bool CanDeploy (SolutionItem entry, MakefileType type) + public bool CanDeploy (SolutionFolderItem entry, MakefileType type) { return entry is SolutionFolder; } - public Makefile Deploy (AutotoolsContext ctx, SolutionItem entry, IProgressMonitor monitor) + public Makefile Deploy (AutotoolsContext ctx, SolutionFolderItem entry, ProgressMonitor monitor) { generateAutotools = ctx.MakefileType == MakefileType.AutotoolsMakefile; @@ -78,10 +78,10 @@ namespace MonoDevelop.Autotools subdirs.Append (" SUBDIRS = "); - foreach (SolutionItem ce in CalculateSubDirOrder (ctx, solutionFolder, config)) + foreach (SolutionFolderItem ce in CalculateSubDirOrder (ctx, solutionFolder, config)) { string baseDirectory; - if (!(ce is SolutionEntityItem) && !(ce is SolutionFolder)) + if (!(ce is SolutionItem) && !(ce is SolutionFolder)) continue; // Ignore projects which can't be deployed @@ -118,7 +118,7 @@ namespace MonoDevelop.Autotools string includedProject = null; // deploy recursively - foreach (SolutionItem ce in children) + foreach (SolutionFolderItem ce in children) { IMakefileHandler handler = AutotoolsContext.GetMakefileHandler ( ce, ctx.MakefileType ); Makefile makefile; @@ -206,11 +206,11 @@ namespace MonoDevelop.Autotools } // utility function for finding the correct order to process directories - List<SolutionItem> CalculateSubDirOrder (AutotoolsContext ctx, SolutionFolder folder, SolutionConfiguration config) + List<SolutionFolderItem> CalculateSubDirOrder (AutotoolsContext ctx, SolutionFolder folder, SolutionConfiguration config) { - List<SolutionItem> resultOrder = new List<SolutionItem>(); - Set<SolutionItem> dependenciesMet = new Set<SolutionItem>(); - Set<SolutionItem> inResult = new Set<SolutionItem>(); + List<SolutionFolderItem> resultOrder = new List<SolutionFolderItem>(); + Set<SolutionFolderItem> dependenciesMet = new Set<SolutionFolderItem>(); + Set<SolutionFolderItem> inResult = new Set<SolutionFolderItem>(); // We don't have to worry about projects built in parent combines dependenciesMet.Union (ctx.GetBuiltProjects ()); @@ -222,24 +222,24 @@ namespace MonoDevelop.Autotools added = false; notMet = null; - List<SolutionItem> items = new List<SolutionItem> (); + List<SolutionFolderItem> items = new List<SolutionFolderItem> (); GetSubItems (items, folder); - foreach (SolutionItem item in items) + foreach (SolutionFolderItem item in items) { - Set<SolutionItem> references, provides; + Set<SolutionFolderItem> references, provides; if (inResult.Contains (item)) continue; - if (item is SolutionEntityItem) + if (item is SolutionItem) { - SolutionEntityItem entry = (SolutionEntityItem) item; + SolutionItem entry = (SolutionItem) item; if (!config.BuildEnabledForItem (entry)) continue; - references = new Set<SolutionItem> (); - provides = new Set<SolutionItem>(); + references = new Set<SolutionFolderItem> (); + provides = new Set<SolutionFolderItem>(); references.Union (entry.GetReferencedItems (config.Selector)); provides.Add (entry); } @@ -266,12 +266,12 @@ namespace MonoDevelop.Autotools return resultOrder; } - void GetSubItems (List<SolutionItem> list, SolutionFolder folder) + void GetSubItems (List<SolutionFolderItem> list, SolutionFolder folder) { // This method returns the subitems of a folder. // If a folder does not match a phisical folder, it will be ignored. - foreach (SolutionItem item in folder.Items) { + foreach (SolutionFolderItem item in folder.Items) { if (item is SolutionFolder) { if (item.BaseDirectory != folder.BaseDirectory) list.Add (item); @@ -290,25 +290,25 @@ namespace MonoDevelop.Autotools * returns a set of projects that a combine contains and a set of projects * that are referenced from combine projects but not part of the combine */ - void GetAllProjects (SolutionFolder folder, SolutionConfiguration config, out Set<SolutionItem> projects, out Set<SolutionItem> references) + void GetAllProjects (SolutionFolder folder, SolutionConfiguration config, out Set<SolutionFolderItem> projects, out Set<SolutionFolderItem> references) { - List<SolutionItem> subitems = new List<SolutionItem> (); + List<SolutionFolderItem> subitems = new List<SolutionFolderItem> (); GetSubItems (subitems, folder); - projects = (Set<SolutionItem>) combineProjects [folder]; + projects = (Set<SolutionFolderItem>) combineProjects [folder]; if (projects != null) { - references = (Set<SolutionItem>) combineReferences [folder]; + references = (Set<SolutionFolderItem>) combineReferences [folder]; return; } - projects = new Set<SolutionItem>(); - references = new Set<SolutionItem>(); + projects = new Set<SolutionFolderItem>(); + references = new Set<SolutionFolderItem>(); - foreach (SolutionItem item in subitems) + foreach (SolutionFolderItem item in subitems) { - if (item is SolutionEntityItem) + if (item is SolutionItem) { - SolutionEntityItem entry = (SolutionEntityItem) item; + SolutionItem entry = (SolutionItem) item; if (!config.BuildEnabledForItem (entry)) continue; projects.Add (entry); @@ -316,8 +316,8 @@ namespace MonoDevelop.Autotools } else if (item is SolutionFolder) { - Set<SolutionItem> subProjects; - Set<SolutionItem> subReferences; + Set<SolutionFolderItem> subProjects; + Set<SolutionFolderItem> subReferences; GetAllProjects ((SolutionFolder)item, config, out subProjects, out subReferences); projects.Union (subProjects); references.Union (subReferences); diff --git a/main/src/addins/MonoDevelop.Autotools/TarballBuilderEditorWidget.cs b/main/src/addins/MonoDevelop.Autotools/TarballBuilderEditorWidget.cs index edd2eebbdd..0ef6aaaf30 100644 --- a/main/src/addins/MonoDevelop.Autotools/TarballBuilderEditorWidget.cs +++ b/main/src/addins/MonoDevelop.Autotools/TarballBuilderEditorWidget.cs @@ -17,7 +17,7 @@ namespace MonoDevelop.Autotools alignment1.Xscale = 0.04f; this.target = target; - SolutionItem targetCombine = target.RootSolutionItem; + SolutionFolderItem targetCombine = target.RootSolutionItem; folderEntry.Path = target.TargetDir; if (string.IsNullOrEmpty (target.DefaultConfiguration)) { diff --git a/main/src/addins/MonoDevelop.Debugger.Gdb/GdbSession.cs b/main/src/addins/MonoDevelop.Debugger.Gdb/GdbSession.cs index f7ad8dfa67..44dc1f91e1 100644 --- a/main/src/addins/MonoDevelop.Debugger.Gdb/GdbSession.cs +++ b/main/src/addins/MonoDevelop.Debugger.Gdb/GdbSession.cs @@ -45,7 +45,7 @@ namespace MonoDevelop.Debugger.Gdb Process proc; StreamReader sout; StreamWriter sin; - IProcessAsyncOperation console; + ProcessAsyncOperation console; GdbCommandResult lastResult; bool running; Thread thread; diff --git a/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/CustomSoftDebuggerEngine.cs b/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/CustomSoftDebuggerEngine.cs index ca3f329233..134809e69f 100644 --- a/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/CustomSoftDebuggerEngine.cs +++ b/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/CustomSoftDebuggerEngine.cs @@ -98,7 +98,7 @@ namespace MonoDevelop.Debugger.Soft class CustomSoftDebuggerSession : SoftDebuggerSession { - IProcessAsyncOperation process; + ProcessAsyncOperation process; bool usingExternalConsole; protected override void OnRun (DebuggerStartInfo startInfo) @@ -138,7 +138,7 @@ namespace MonoDevelop.Debugger.Soft foreach (KeyValuePair<string,string> kvp in info.EnvironmentVariables) psi.EnvironmentVariables [kvp.Key] = kvp.Value; - process = Runtime.ProcessService.StartProcess (psi, ProcessOutput, ProcessError, null); + process = Runtime.ProcessService.StartProcess (psi, ProcessOutput, ProcessError, null).ProcessAsyncOperation; } } diff --git a/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/SoftDebuggerEngine.cs b/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/SoftDebuggerEngine.cs index f04bc311f4..190ab55c6a 100644 --- a/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/SoftDebuggerEngine.cs +++ b/main/src/addins/MonoDevelop.Debugger.Soft/MonoDevelop.Debugger.Soft/SoftDebuggerEngine.cs @@ -86,7 +86,7 @@ namespace MonoDevelop.Debugger.Soft var varsCopy = new Dictionary<string, string> (cmd.EnvironmentVariables); var startArgs = (SoftDebuggerLaunchArgs) dsi.StartArgs; startArgs.ExternalConsoleLauncher = delegate (System.Diagnostics.ProcessStartInfo info) { - IProcessAsyncOperation oper; + ProcessAsyncOperation oper; oper = Runtime.ProcessService.StartConsoleProcess (info.FileName, info.Arguments, info.WorkingDirectory, varsCopy, ExternalConsoleFactory.Instance.CreateConsole (dsi.CloseExternalConsoleOnExit), null); return new ProcessAdapter (oper, Path.GetFileName (info.FileName)); @@ -158,17 +158,17 @@ namespace MonoDevelop.Debugger.Soft class ProcessAdapter: Mono.Debugger.Soft.ITargetProcess { - IProcessAsyncOperation oper; + ProcessAsyncOperation oper; string name; - public ProcessAdapter (IProcessAsyncOperation oper, string name) + public ProcessAdapter (ProcessAsyncOperation oper, string name) { this.oper = oper; this.name = name; - oper.Completed += delegate { + oper.Task.ContinueWith (t => { if (Exited != null) Exited (this, EventArgs.Empty); - }; + }); } #region IProcess implementation diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs index 5caa63f289..23dd037508 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs @@ -64,6 +64,8 @@ namespace MonoDevelop.Debugger.Win32 public override bool IsEnum (EvaluationContext ctx, object val)
{
+ if (!(val is CorValRef))
+ return false;
CorType type = (CorType) GetValueType (ctx, val);
return IsEnum (ctx, type);
}
diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.Visualizer/TextVisualizer.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.Visualizer/TextVisualizer.cs index cb2b881229..64b1153aea 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.Visualizer/TextVisualizer.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.Visualizer/TextVisualizer.cs @@ -106,12 +106,12 @@ namespace MonoDevelop.Debugger.Visualizer void PopulateTextView (ObjectValue value) { - var ops = DebuggingService.DebuggerSession.EvaluationOptions.Clone (); - ops.AllowTargetInvoke = true; - ops.ChunkRawStrings = true; + var options = DebuggingService.DebuggerSession.EvaluationOptions.Clone (); + options.AllowTargetInvoke = true; + options.ChunkRawStrings = true; if (value.TypeName == "string") { - rawString = value.GetRawValue (ops) as RawValueString; + rawString = value.GetRawValue (options) as RawValueString; length = rawString.Length; offset = 0; @@ -125,7 +125,7 @@ namespace MonoDevelop.Debugger.Visualizer }; } } else if (value.TypeName == "char[]") { - rawArray = value.GetRawValue (ops) as RawValueArray; + rawArray = value.GetRawValue (options) as RawValueArray; length = rawArray.Length; offset = 0; @@ -173,12 +173,15 @@ namespace MonoDevelop.Debugger.Visualizer public override bool StoreValue (ObjectValue val) { + var options = DebuggingService.DebuggerSession.EvaluationOptions.Clone (); + options.AllowTargetInvoke = true; + switch (val.TypeName) { case "char[]": - val.SetRawValue (textView.Buffer.Text.ToCharArray ()); + val.SetRawValue (textView.Buffer.Text.ToCharArray (), options); return true; case "string": - val.SetRawValue (textView.Buffer.Text); + val.SetRawValue (textView.Buffer.Text, options); return true; default: return false; diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.addin.xml b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.addin.xml index 402df196c7..19045ebe26 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.addin.xml +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger.addin.xml @@ -102,8 +102,20 @@ icon="md-step-out-debug"/> <Command id = "MonoDevelop.Debugger.DebugCommands.NewBreakpoint" defaultHandler = "MonoDevelop.Debugger.NewBreakpointHandler" - _label = "New Breakpoint..." + _label = "New Breakpoint" icon = "md-breakpoint-new" /> + <Command id = "MonoDevelop.Debugger.DebugCommands.NewFunctionBreakpoint" + defaultHandler = "MonoDevelop.Debugger.NewFunctionBreakpointHandler" + _label = "New Function Breakpoint" + icon = "md-breakpoint-new" /> + <Command id = "MonoDevelop.Debugger.DebugCommands.NewCatchpoint" + defaultHandler = "MonoDevelop.Debugger.NewCatchpointHandler" + _label = "New Exception Catchpoint" + icon = "md-breakpoint-new" /> + <Command id = "MonoDevelop.Debugger.DebugCommands.ShowBreakpoints" + defaultHandler = "MonoDevelop.Debugger.ShowBreakpointsHandler" + _label = "View Breakpoints" + icon = "md-view-debug-breakpoints" /> <Command id = "MonoDevelop.Debugger.DebugCommands.RemoveBreakpoint" defaultHandler = "MonoDevelop.Debugger.RemoveBreakpointHandler" _label = "Remove Breakpoint" /> @@ -183,6 +195,9 @@ <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ShowCurrentExecutionLine" /> <SeparatorItem id = "MonoDevelop.Debugger.BreakpointsSection" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.NewBreakpoint" /> + <CommandItem id = "MonoDevelop.Debugger.DebugCommands.NewFunctionBreakpoint" /> + <CommandItem id = "MonoDevelop.Debugger.DebugCommands.NewCatchpoint" /> + <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ShowBreakpoints" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.ToggleBreakpoint" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.EnableDisableBreakpoint" /> <CommandItem id = "MonoDevelop.Debugger.DebugCommands.DisableAllBreakpoints" /> diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPad.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPad.cs index 29742d7fd4..f468753ed1 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPad.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPad.cs @@ -98,6 +98,9 @@ namespace MonoDevelop.Debugger toolbarSet.AddItem (EditCommands.Delete); toolbarSet.AddSeparator (); toolbarSet.Add (propertiesCmd); + toolbarSet.AddSeparator (); + toolbarSet.Add (new CommandEntry (DebugCommands.NewFunctionBreakpoint){ DispayType = CommandEntryDisplayType.IconAndText }); + toolbarSet.Add (new CommandEntry (DebugCommands.NewCatchpoint){ DispayType = CommandEntryDisplayType.IconAndText }); // The breakpoint list diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPropertiesDialog.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPropertiesDialog.cs index 683bc1d2e2..1df779cacc 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPropertiesDialog.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/BreakpointPropertiesDialog.cs @@ -46,6 +46,13 @@ namespace MonoDevelop.Debugger ExpressionChanges
}
+ public enum BreakpointType
+ {
+ Location,
+ Function,
+ Catchpoint
+ }
+
sealed class BreakpointPropertiesDialog : Dialog
{
// For button sensitivity.
@@ -193,15 +200,29 @@ namespace MonoDevelop.Debugger string parsedFunction;
readonly HashSet<string> classes = new HashSet<string> ();
-
- public BreakpointPropertiesDialog (BreakEvent be)
+ public BreakpointPropertiesDialog (BreakEvent be, BreakpointType breakpointType)
{
this.be = be;
-
LoadExceptionList ();
Initialize ();
SetInitialData ();
SetLayout ();
+ if (be == null) {
+ switch (breakpointType) {
+ case BreakpointType.Location:
+ stopOnLocation.Active = true;
+ entryLocationFile.SetFocus ();
+ break;
+ case BreakpointType.Function:
+ stopOnFunction.Active = true;
+ entryFunctionName.SetFocus ();
+ break;
+ case BreakpointType.Catchpoint:
+ stopOnException.Active = true;
+ entryExceptionType.SetFocus ();
+ break;
+ }
+ }
}
void Initialize ()
@@ -258,8 +279,46 @@ namespace MonoDevelop.Debugger entryPrintExpression.Changed += OnUpdateText;
buttonOk.Clicked += OnSave;
+
+ CompletionWindowManager.WindowShown += HandleCompletionWindowShown;
+ CompletionWindowManager.WindowClosed += HandleCompletionWindowClosed;
}
+ #region Modal and Dialog.Run workaround
+ /*
+ * If Dialog is ran with Dialog.Run and Modal=true it takes all events like mouse, keyboard... from other windows.
+ * So when CodeCompletionList window appears mouse events don't work on it(except if CodeCompletionList.Modal=true, but then
+ * events don't work on BreakpointPropertiesDialog(can't type rest of exception type name)).
+ * So what this workaround does is disables Modal on BreakpointProperties so CodeCompletionList mouse events work fine. But if user
+ * tries to access anything outside this two windows(e.g. MainWindow). CodeCompletionList loses focus and closes itself. Resulting
+ * in BreakpointProperties.Modal = true and user can't do anything on MainWindow.
+ * All this is done so fast(or in correct order) that user can't notice this Modal switching.
+ */
+
+ void HandleCompletionWindowClosed (object sender, EventArgs e)
+ {
+ var gtkWidget = Xwt.Toolkit.CurrentEngine.GetNativeWidget (vboxLocation) as Gtk.Widget;//Any widget is fine
+ if (gtkWidget != null) {
+ var topWindow = gtkWidget.Toplevel as Gtk.Window;
+ if (topWindow != null) {
+ topWindow.Modal = true;
+ }
+ }
+ }
+
+ void HandleCompletionWindowShown (object sender, EventArgs e)
+ {
+ var gtkWidget = Xwt.Toolkit.CurrentEngine.GetNativeWidget (vboxLocation) as Gtk.Widget;//Any widget is fine
+ if (gtkWidget != null) {
+ var topWindow = gtkWidget.Toplevel as Gtk.Window;
+ if (topWindow != null) {
+ topWindow.Modal = false;
+ }
+ }
+ }
+
+ #endregion
+
void SetInitialFunctionBreakpointData (FunctionBreakpoint fb)
{
stopOnLocation.Visible = false;
@@ -292,7 +351,7 @@ namespace MonoDevelop.Debugger if (project != null) {
// Check the startup project of the solution too, since the current project may be a library
- SolutionEntityItem startup = project.ParentSolution.StartupItem;
+ SolutionItem startup = project.ParentSolution.StartupItem;
entryConditionalExpression.Sensitive = DebuggingService.IsFeatureSupported (project, DebuggerFeatures.ConditionalBreakpoints) ||
DebuggingService.IsFeatureSupported (startup, DebuggerFeatures.ConditionalBreakpoints);
@@ -758,5 +817,11 @@ namespace MonoDevelop.Debugger OnUpdateControls (null, null);
}
+ protected override void Dispose (bool disposing)
+ {
+ CompletionWindowManager.WindowShown -= HandleCompletionWindowShown;
+ CompletionWindowManager.WindowClosed -= HandleCompletionWindowClosed;
+ base.Dispose (disposing);
+ }
}
}
\ No newline at end of file diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugCommands.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugCommands.cs index 56c6f5cb5a..9c311dc928 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugCommands.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugCommands.cs @@ -34,6 +34,7 @@ using MonoDevelop.Ide.Gui; using MonoDevelop.Components.Commands; using MonoDevelop.Projects; using MonoDevelop.Ide; +using System.Linq; namespace MonoDevelop.Debugger { @@ -63,7 +64,9 @@ namespace MonoDevelop.Debugger StopEvaluation, RunToCursor, SetNextStatement, - ShowNextStatement + ShowNextStatement, + NewCatchpoint, + NewFunctionBreakpoint } class DebugHandler: CommandHandler @@ -75,7 +78,7 @@ namespace MonoDevelop.Debugger IdeApp.ProjectOperations.CurrentSelectedBuildTarget; } - internal static void BuildAndDebug () + internal async static void BuildAndDebug () { if (!DebuggingService.IsDebuggingSupported && !IdeApp.ProjectOperations.CurrentRunOperation.IsCompleted) { MonoDevelop.Ide.Commands.StopHandler.StopBuildOperations (); @@ -94,33 +97,14 @@ namespace MonoDevelop.Debugger } // Else continue building } - else { - ExecuteDocument (IdeApp.Workbench.ActiveDocument); - return; - } } if (IdeApp.Workspace.IsOpen) { var it = GetRunTarget (); - IAsyncOperation op = IdeApp.ProjectOperations.Build (it); - op.Completed += delegate { - if (op.SuccessWithWarnings && !IdeApp.Preferences.RunWithWarnings) - return; - if (op.Success) - ExecuteSolution (it); - }; - } else { - Document doc = IdeApp.Workbench.ActiveDocument; - if (doc != null) { - doc.Save (); - IAsyncOperation op = doc.Build (); - op.Completed += delegate { - if (op.SuccessWithWarnings && !IdeApp.Preferences.RunWithWarnings) - return; - if (op.Success) - ExecuteDocument (doc); - }; - } + var res = await IdeApp.ProjectOperations.Build (it).Task; + if (res.HasErrors || (res.HasWarnings && !IdeApp.Preferences.RunWithWarnings)) + return; + ExecuteSolution (it); } } @@ -132,14 +116,6 @@ namespace MonoDevelop.Debugger IdeApp.ProjectOperations.Execute (target); } - static void ExecuteDocument (Document doc) - { - if (doc.CanDebug ()) - doc.Debug (); - else - doc.Run (); - } - protected override void Run () { if (DebuggingService.IsPaused) { @@ -180,8 +156,7 @@ namespace MonoDevelop.Debugger info.Enabled = canExecute && (IdeApp.ProjectOperations.CurrentRunOperation.IsCompleted || !DebuggingService.IsDebuggingSupported); } else { - Document doc = IdeApp.Workbench.ActiveDocument; - info.Enabled = (doc != null && doc.IsBuildTarget) && (doc.CanRun () || doc.CanDebug ()); + info.Enabled = false; } } @@ -226,19 +201,16 @@ namespace MonoDevelop.Debugger class DebugEntryHandler: CommandHandler { - protected override void Run () + protected async override void Run () { IBuildTarget entry = IdeApp.ProjectOperations.CurrentSelectedBuildTarget; DebugHandler.CheckResult cr = DebugHandler.CheckBeforeDebugging (entry); if (cr == DebugHandler.CheckResult.BuildBeforeRun) { - IAsyncOperation op = IdeApp.ProjectOperations.Build (entry); - op.Completed += delegate { - if (op.SuccessWithWarnings && !IdeApp.Preferences.RunWithWarnings) - return; - if (op.Success) - IdeApp.ProjectOperations.Debug (entry); - }; + var res = await IdeApp.ProjectOperations.Build (entry).Task; + if (res.HasErrors || (res.HasWarnings && !IdeApp.Preferences.RunWithWarnings)) + return; + IdeApp.ProjectOperations.Debug (entry); } else if (cr == DebugHandler.CheckResult.Run) IdeApp.ProjectOperations.Debug (entry); } @@ -535,7 +507,7 @@ namespace MonoDevelop.Debugger } } } - + class NewBreakpointHandler: CommandHandler { protected override void Run () @@ -548,7 +520,27 @@ namespace MonoDevelop.Debugger breakpoints.Add (bp); } } - + + protected override void Update (CommandInfo info) + { + info.Visible = DebuggingService.IsFeatureSupported (DebuggerFeatures.Breakpoints); + info.Enabled = !DebuggingService.Breakpoints.IsReadOnly; + } + } + + class NewFunctionBreakpointHandler: CommandHandler + { + protected override void Run () + { + BreakEvent bp = null; + if (DebuggingService.ShowBreakpointProperties (ref bp, BreakpointType.Function)) { + var breakpoints = DebuggingService.Breakpoints; + + lock (breakpoints) + breakpoints.Add (bp); + } + } + protected override void Update (CommandInfo info) { info.Visible = DebuggingService.IsFeatureSupported (DebuggerFeatures.Breakpoints); @@ -556,6 +548,37 @@ namespace MonoDevelop.Debugger } } + class NewCatchpointHandler: CommandHandler + { + protected override void Run () + { + BreakEvent bp = null; + if (DebuggingService.ShowBreakpointProperties (ref bp, BreakpointType.Catchpoint)) { + var breakpoints = DebuggingService.Breakpoints; + + lock (breakpoints) + breakpoints.Add (bp); + } + } + + protected override void Update (CommandInfo info) + { + info.Visible = DebuggingService.IsFeatureSupported (DebuggerFeatures.Catchpoints); + info.Enabled = !DebuggingService.Breakpoints.IsReadOnly; + } + } + + class ShowBreakpointsHandler: CommandHandler + { + protected override void Run () + { + var breakpointsPad = IdeApp.Workbench.Pads.FirstOrDefault (p => p.Id == "MonoDevelop.Debugger.BreakpointPad"); + if (breakpointsPad != null) { + breakpointsPad.BringToFront (); + } + } + } + class RunToCursorHandler : CommandHandler { protected override void Run () @@ -589,7 +612,7 @@ namespace MonoDevelop.Debugger info.Enabled = target != null && IdeApp.ProjectOperations.CanDebug (target); } else { - info.Enabled = doc.IsBuildTarget && doc.CanDebug (); + info.Enabled = false; } } else { info.Enabled = false; diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugExecutionHandlerFactory.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugExecutionHandlerFactory.cs index 55cc770269..df9f1806d2 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugExecutionHandlerFactory.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebugExecutionHandlerFactory.cs @@ -34,6 +34,7 @@ using MonoDevelop.Core.Execution; using Mono.Debugging.Client; using MonoDevelop.Ide.Gui; using Mono.Debugging; +using System.Threading.Tasks; namespace MonoDevelop.Debugger { @@ -44,103 +45,36 @@ namespace MonoDevelop.Debugger return DebuggingService.CanDebugCommand (command); } - public IProcessAsyncOperation Execute (ExecutionCommand command, IConsole console) + public ProcessAsyncOperation Execute (ExecutionCommand command, IConsole console) { if (!CanExecute (command)) return null; - DebugExecutionHandler h = new DebugExecutionHandler (null); - return h.Execute (command, console); + return DebuggingService.Run (command, console); } } - - class DebugExecutionHandler: IProcessAsyncOperation + + class DebugAsyncOperation: ProcessAsyncOperation { - bool done; ManualResetEvent stopEvent; - DebuggerEngine factory; - - public DebugExecutionHandler (DebuggerEngine factory) - { - this.factory = factory; - DebuggingService.StoppedEvent += new EventHandler (OnStopDebug); - } - - public IProcessAsyncOperation Execute (ExecutionCommand command, IConsole console) - { - DebuggingService.InternalRun (command, factory, console); - return this; - } - - public void Cancel () - { - DebuggingService.Stop (); - } - - public void WaitForCompleted () + + public DebugAsyncOperation () { - lock (this) { - if (done) return; - if (stopEvent == null) - stopEvent = new ManualResetEvent (false); - } - stopEvent.WaitOne (); - } - - public int ExitCode { - get { return 0; } - } - - public bool IsCompleted { - get { return done; } - } - - public bool Success { - get { return true; } + stopEvent = new ManualResetEvent (false); + DebuggingService.StoppedEvent += OnStopDebug; + CancellationTokenSource = new CancellationTokenSource (); + CancellationTokenSource.Token.Register (DebuggingService.Stop); + Task = Task.Factory.StartNew (() => stopEvent.WaitOne ()); } - public bool SuccessWithWarnings { - get { return true; } + public void Cleanup () + { + stopEvent.Set (); // Just in case there was something running + DebuggingService.StoppedEvent -= OnStopDebug; } void OnStopDebug (object sender, EventArgs args) { - lock (this) { - done = true; - if (stopEvent != null) - stopEvent.Set (); - if (completedEvent != null) - completedEvent (this); - } - - DebuggingService.StoppedEvent -= new EventHandler (OnStopDebug); - } - - event OperationHandler IAsyncOperation.Completed { - add { - bool raiseNow = false; - lock (this) { - if (done) - raiseNow = true; - else - completedEvent += value; - } - if (raiseNow) - value (this); - } - remove { - lock (this) { - completedEvent -= value; - } - } - } - - //FIXME: - public int ProcessId { - get { return -1; } + stopEvent.Set (); } - - event OperationHandler completedEvent; - - void IDisposable.Dispose () {} } } diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebuggingService.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebuggingService.cs index 31b1c55808..05050e81b0 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebuggingService.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/DebuggingService.cs @@ -46,6 +46,7 @@ using ICSharpCode.NRefactory.Semantics; */ using MonoDevelop.Ide.TextEditing; using System.Linq; +using System.Threading.Tasks; namespace MonoDevelop.Debugger { @@ -76,6 +77,8 @@ namespace MonoDevelop.Debugger static StatusBarIcon busyStatusIcon; static bool isBusy; + static DebugAsyncOperation currentDebugOperation = new DebugAsyncOperation (); + static public event EventHandler DebugSessionStarted; static public event EventHandler PausedEvent; static public event EventHandler ResumedEvent; @@ -187,9 +190,9 @@ namespace MonoDevelop.Debugger MessageService.ShowCustomDialog (dlg); } - public static bool ShowBreakpointProperties (ref BreakEvent bp) + public static bool ShowBreakpointProperties (ref BreakEvent bp, BreakpointType breakpointType = BreakpointType.Location) { - using (var dlg = new BreakpointPropertiesDialog (bp)) { + using (var dlg = new BreakpointPropertiesDialog (bp, breakpointType)) { Xwt.Command response = dlg.Run (); if (bp == null) bp = dlg.GetBreakEvent (); @@ -303,6 +306,7 @@ namespace MonoDevelop.Debugger session.ConnectionDialogCreator = delegate { return new StatusBarConnectionDialog (); }; + currentDebugOperation = new DebugAsyncOperation (); console.CancelRequested += OnCancelRequested; @@ -353,7 +357,8 @@ namespace MonoDevelop.Debugger currentSession.TypeResolverHandler = null; currentSession.OutputWriter = null; currentSession.LogWriter = null; - + currentDebugOperation.Cleanup (); + if (currentConsole != null) { currentConsole.CancelRequested -= OnCancelRequested; currentConsole.Dispose (); @@ -460,20 +465,24 @@ namespace MonoDevelop.Debugger NotifyLocationChanged (); } - public static IProcessAsyncOperation Run (string file, IConsole console) + public static ProcessAsyncOperation Run (string file, IConsole console) { - var h = new DebugExecutionHandler (null); var cmd = Runtime.ProcessService.CreateCommand (file); + return Run (cmd, console); + } - return h.Execute (cmd, console); + public static ProcessAsyncOperation Run (ExecutionCommand cmd, IConsole console, DebuggerEngine engine = null) + { + InternalRun (cmd, engine, console); + return currentDebugOperation; } - public static IAsyncOperation AttachToProcess (DebuggerEngine debugger, ProcessInfo proc) + public static AsyncOperation AttachToProcess (DebuggerEngine debugger, ProcessInfo proc) { currentEngine = debugger; session = debugger.CreateSession (); session.ExceptionHandler = ExceptionHandler; - IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor (); + ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor (); console = monitor as IConsole; SetupSession (); session.TargetExited += delegate { @@ -481,7 +490,7 @@ namespace MonoDevelop.Debugger }; SetDebugLayout (); session.AttachToProcess (proc, GetUserOptions ()); - return monitor.AsyncOperation; + return currentDebugOperation; } public static DebuggerSessionOptions GetUserOptions () @@ -1022,7 +1031,7 @@ namespace MonoDevelop.Debugger return SupportedFeatures != DebuggerFeatures.None; } - public IProcessAsyncOperation Execute (ExecutionCommand cmd, IConsole console) + public ProcessAsyncOperation Execute (ExecutionCommand cmd, IConsole console) { // Never called throw new NotImplementedException (); @@ -1043,10 +1052,9 @@ namespace MonoDevelop.Debugger return engine.CanDebugCommand (command); } - public IProcessAsyncOperation Execute (ExecutionCommand command, IConsole console) + public ProcessAsyncOperation Execute (ExecutionCommand command, IConsole console) { - var h = new DebugExecutionHandler (engine); - return h.Execute (command, console); + return DebuggingService.Run (command, console, engine); } } diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ExceptionCaughtDialog.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ExceptionCaughtDialog.cs index b8dc53e274..6b65ff6c34 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ExceptionCaughtDialog.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ExceptionCaughtDialog.cs @@ -27,6 +27,7 @@ using System; using System.IO; +using System.Linq; using Gtk; @@ -74,8 +75,8 @@ namespace MonoDevelop.Debugger Widget CreateExceptionInfoHeader () { - ExceptionMessageLabel = new Label () { UseMarkup = true, Selectable = true, Wrap = true, WidthRequest = 500, Xalign = 0.0f, Yalign = 0.0f }; - ExceptionTypeLabel = new Label () { UseMarkup = true, Xalign = 0.0f }; + ExceptionMessageLabel = new Label { UseMarkup = true, Selectable = true, Wrap = true, WidthRequest = 500, Xalign = 0.0f, Yalign = 0.0f }; + ExceptionTypeLabel = new Label { UseMarkup = true, Xalign = 0.0f }; ExceptionMessageLabel.Show (); ExceptionTypeLabel.Show (); @@ -124,7 +125,7 @@ namespace MonoDevelop.Debugger ExceptionValueTreeView.Selection.Changed += ExceptionValueSelectionChanged; ExceptionValueTreeView.Show (); - var scrolled = new ScrolledWindow () { HeightRequest = 180 }; + var scrolled = new ScrolledWindow { HeightRequest = 180, HscrollbarPolicy = PolicyType.Automatic, VscrollbarPolicy = PolicyType.Automatic }; scrolled.ShadowType = ShadowType.None; scrolled.Add (ExceptionValueTreeView); @@ -138,17 +139,21 @@ namespace MonoDevelop.Debugger var frame = (ExceptionStackFrame) model.GetValue (iter, (int) ModelColumn.StackFrame); var renderer = (StackFrameCellRenderer) cr; - if (!(renderer.IsStackFrame = frame != null)) + renderer.Markup = (string) model.GetValue (iter, (int) ModelColumn.Markup); + + if (!(renderer.IsStackFrame = frame != null)) { + renderer.IsUserCode = false; + renderer.LineNumber = -1; return; + } renderer.IsUserCode = (bool) model.GetValue (iter, (int) ModelColumn.IsUserCode); renderer.LineNumber = !string.IsNullOrEmpty (frame.File) ? frame.Line : -1; - renderer.Markup = (string) model.GetValue (iter, (int) ModelColumn.Markup); } Widget CreateStackTraceTreeView () { - var store = new ListStore (typeof (ExceptionStackFrame), typeof (string), typeof (bool), typeof (int), typeof (int)); + var store = new ListStore (typeof (ExceptionStackFrame), typeof (string), typeof (bool)); StackTraceTreeView = new TreeView (store); StackTraceTreeView.FixedHeightMode = false; StackTraceTreeView.HeadersVisible = false; @@ -164,7 +169,7 @@ namespace MonoDevelop.Debugger StackTraceTreeView.SizeAllocated += (o, args) => renderer.Width = args.Allocation.Width; StackTraceTreeView.RowActivated += StackFrameActivated; - var scrolled = new ScrolledWindow () { HeightRequest = 180 }; + var scrolled = new ScrolledWindow { HeightRequest = 180, HscrollbarPolicy = PolicyType.Automatic, VscrollbarPolicy = PolicyType.Automatic }; scrolled.ShadowType = ShadowType.None; scrolled.Add (StackTraceTreeView); scrolled.Show (); @@ -174,7 +179,7 @@ namespace MonoDevelop.Debugger Widget CreateButtonBox () { - var buttons = new HButtonBox () { Layout = ButtonBoxStyle.End, Spacing = 12 }; + var buttons = new HButtonBox { Layout = ButtonBoxStyle.End, Spacing = 12 }; var copy = new Button (Stock.Copy); copy.Clicked += CopyClicked; @@ -194,7 +199,7 @@ namespace MonoDevelop.Debugger return buttons; } - Widget CreateSeparator () + static Widget CreateSeparator () { var separator = new HSeparator (); separator.Show (); @@ -297,7 +302,7 @@ namespace MonoDevelop.Debugger if (frame != null && !string.IsNullOrEmpty (frame.File) && File.Exists (frame.File)) { try { - IdeApp.Workbench.OpenDocument (frame.File, null, frame.Line, frame.Column); + IdeApp.Workbench.OpenDocument (frame.File, null, frame.Line, frame.Column, MonoDevelop.Ide.Gui.OpenDocumentOptions.Debugger); } catch (FileNotFoundException) { } } @@ -308,7 +313,7 @@ namespace MonoDevelop.Debugger if (frame == null || string.IsNullOrEmpty (frame.File)) return false; - return IdeApp.Workspace.GetProjectContainingFile (frame.File) != null; + return IdeApp.Workspace.GetProjectsContainingFile (frame.File).Any (); } void ShowStackTrace (ExceptionInfo ex) @@ -633,11 +638,11 @@ namespace MonoDevelop.Debugger class ExceptionCaughtButton: TopLevelWidgetExtension { + readonly Xwt.Drawing.Image closeSelOverImage; + readonly Xwt.Drawing.Image closeSelImage; readonly ExceptionCaughtMessage dlg; readonly ExceptionInfo exception; - Gtk.Label messageLabel; - readonly Xwt.Drawing.Image closeSelImage; - readonly Xwt.Drawing.Image closeSelOverImage; + Label messageLabel; public ExceptionCaughtButton (ExceptionInfo val, ExceptionCaughtMessage dlg, FilePath file, int line) { @@ -667,23 +672,23 @@ namespace MonoDevelop.Debugger var icon = Xwt.Drawing.Image.FromResource ("lightning-light-16.png"); var image = new Xwt.ImageView (icon).ToGtkWidget (); - HBox box = new HBox (false, 6); - VBox vb = new VBox (); + var box = new HBox (false, 6); + var vb = new VBox (); vb.PackStart (image, false, false, 0); box.PackStart (vb, false, false, 0); vb = new VBox (false, 6); - vb.PackStart (new Gtk.Label () { + vb.PackStart (new Label { Markup = GettextCatalog.GetString ("<b>{0}</b> has been thrown", exception.Type), Xalign = 0 }); - messageLabel = new Gtk.Label () { + messageLabel = new Label { Xalign = 0, NoShowAll = true }; vb.PackStart (messageLabel); var detailsBtn = new Xwt.LinkLabel (GettextCatalog.GetString ("Show Details")); - HBox hh = new HBox (); + var hh = new HBox (); detailsBtn.NavigateToUrl += (o,e) => dlg.ShowDialog (); hh.PackStart (detailsBtn.ToGtkWidget (), false, false, 0); vb.PackStart (hh, false, false, 0); @@ -691,7 +696,7 @@ namespace MonoDevelop.Debugger box.PackStart (vb, true, true, 0); vb = new VBox (); - var closeButton = new ImageButton () { + var closeButton = new ImageButton { InactiveImage = closeSelImage, Image = closeSelOverImage }; @@ -708,7 +713,7 @@ namespace MonoDevelop.Debugger }; LoadData (); - PopoverWidget eb = new PopoverWidget (); + var eb = new PopoverWidget (); eb.ShowArrow = true; eb.EnableAnimation = true; eb.PopupPosition = PopupPosition.Left; @@ -758,12 +763,12 @@ namespace MonoDevelop.Debugger public override Widget CreateWidget () { - Gtk.EventBox box = new EventBox (); + var box = new EventBox (); box.VisibleWindow = false; var icon = Xwt.Drawing.Image.FromResource ("lightning-light-16.png"); box.Add (new Xwt.ImageView (icon).ToGtkWidget ()); box.ButtonPressEvent += (o,e) => dlg.ShowButton (); - PopoverWidget eb = new PopoverWidget (); + var eb = new PopoverWidget (); eb.Theme.Padding = 2; eb.ShowArrow = true; eb.EnableAnimation = true; diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/Extensions.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/Extensions.cs index 12d1eb8c51..3d929f96c0 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/Extensions.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/Extensions.cs @@ -42,14 +42,14 @@ namespace MonoDevelop.Debugger return opers.CanExecute (entry, context); } - public static IAsyncOperation Debug (this ProjectOperations opers, IBuildTarget entry) + public static AsyncOperation Debug (this ProjectOperations opers, IBuildTarget entry) { if (opers.CurrentRunOperation != null && !opers.CurrentRunOperation.IsCompleted) return opers.CurrentRunOperation; ExecutionContext context = new ExecutionContext (DebuggingService.GetExecutionHandler (), IdeApp.Workbench.ProgressMonitors, IdeApp.Workspace.ActiveExecutionTarget); - IAsyncOperation op = opers.Execute (entry, context); + AsyncOperation op = opers.Execute (entry, context); SwitchToDebugLayout (op); return op; } @@ -60,13 +60,13 @@ namespace MonoDevelop.Debugger return opers.CanExecuteFile (file, context); } - public static IAsyncOperation DebugFile (this ProjectOperations opers, string file) + public static AsyncOperation DebugFile (this ProjectOperations opers, string file) { var context = new ExecutionContext (DebuggingService.GetExecutionHandler (), IdeApp.Workbench.ProgressMonitors, IdeApp.Workspace.ActiveExecutionTarget); return opers.ExecuteFile (file, context); } - public static IAsyncOperation DebugApplication (this ProjectOperations opers, string executableFile) + public static AsyncOperation DebugApplication (this ProjectOperations opers, string executableFile) { if (opers.CurrentRunOperation != null && !opers.CurrentRunOperation.IsCompleted) return opers.CurrentRunOperation; @@ -77,18 +77,17 @@ namespace MonoDevelop.Debugger var monitor = IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor (); var oper = DebuggingService.Run (executableFile, (IConsole) monitor); - oper.Completed += delegate { + opers.CurrentRunOperation = oper; + + oper.Task.ContinueWith (t => { monitor.Dispose (); - Gtk.Application.Invoke (delegate { - IdeApp.Workbench.CurrentLayout = oldLayout; - }); - }; + IdeApp.Workbench.CurrentLayout = oldLayout; + }); - opers.CurrentRunOperation = monitor.AsyncOperation; - return opers.CurrentRunOperation; + return oper; } - public static IAsyncOperation AttachToProcess (this ProjectOperations opers, DebuggerEngine debugger, ProcessInfo proc) + public static AsyncOperation AttachToProcess (this ProjectOperations opers, DebuggerEngine debugger, ProcessInfo proc) { if (opers.CurrentRunOperation != null && !opers.CurrentRunOperation.IsCompleted) return opers.CurrentRunOperation; @@ -100,26 +99,14 @@ namespace MonoDevelop.Debugger return opers.CurrentRunOperation; } - public static IAsyncOperation Debug (this Document doc) - { - return IdeApp.ProjectOperations.DebugFile (doc.FileName); - } - - public static bool CanDebug (this Document doc) - { - return doc.FileName != FilePath.Null && IdeApp.ProjectOperations.CanDebugFile (doc.FileName); - } - - static void SwitchToDebugLayout (IAsyncOperation oper) + static void SwitchToDebugLayout (AsyncOperation oper) { string oldLayout = IdeApp.Workbench.CurrentLayout; IdeApp.Workbench.CurrentLayout = "Debug"; - oper.Completed += delegate { - DispatchService.GuiDispatch (delegate { - IdeApp.Workbench.CurrentLayout = oldLayout; - }); - }; + oper.Task.ContinueWith (t => { + IdeApp.Workbench.CurrentLayout = oldLayout; + }); } } } diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ObjectValueTreeView.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ObjectValueTreeView.cs index 04a92599ca..892f150861 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ObjectValueTreeView.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ObjectValueTreeView.cs @@ -558,14 +558,14 @@ namespace MonoDevelop.Debugger parent = TreeIter.Zero; if (CanQueryDebugger && frame != null) { - EvaluationOptions ops = frame.DebuggerSession.Options.EvaluationOptions.Clone (); - ops.AllowMethodEvaluation = true; - ops.AllowToStringCalls = true; - ops.AllowTargetInvoke = true; - ops.EllipsizeStrings = false; + var options = frame.DebuggerSession.Options.EvaluationOptions.Clone (); + options.AllowMethodEvaluation = true; + options.AllowToStringCalls = true; + options.AllowTargetInvoke = true; + options.EllipsizeStrings = false; string oldName = val.Name; - val.Refresh (ops); + val.Refresh (options); // Don't update the name for the values entered by the user if (store.IterDepth (iter) == 0) diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ThreadsPad.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ThreadsPad.cs index b20d6f1952..85c087e1b5 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ThreadsPad.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ThreadsPad.cs @@ -186,13 +186,14 @@ namespace MonoDevelop.Debugger foreach (var thread in threads) { ThreadInfo activeThread = DebuggingService.DebuggerSession.ActiveThread; + var name = thread.Name == null && thread.Id == 1 ? "Main Thread" : thread.Name; var weight = thread == activeThread ? Pango.Weight.Bold : Pango.Weight.Normal; var icon = thread == activeThread ? Gtk.Stock.GoForward : null; if (iter.Equals (TreeIter.Zero)) - store.AppendValues (icon, thread.Id.ToString (), thread.Name, thread, (int) weight, thread.Location); + store.AppendValues (icon, thread.Id.ToString (), name, thread, (int) weight, thread.Location); else - store.AppendValues (iter, icon, thread.Id.ToString (), thread.Name, thread, (int) weight, thread.Location); + store.AppendValues (iter, icon, thread.Id.ToString (), name, thread, (int) weight, thread.Location); } } @@ -233,7 +234,7 @@ namespace MonoDevelop.Debugger void OnRowActivated (object s, RowActivatedArgs args) { - TreeIter iter, selected; + TreeIter selected; if (!tree.Selection.GetSelected (out selected)) return; diff --git a/main/src/addins/MonoDevelop.Debugger/gtk-gui/MonoDevelop.Debugger.BusyEvaluatorDialog.cs b/main/src/addins/MonoDevelop.Debugger/gtk-gui/MonoDevelop.Debugger.BusyEvaluatorDialog.cs index d496a65960..20c77c6ed8 100644 --- a/main/src/addins/MonoDevelop.Debugger/gtk-gui/MonoDevelop.Debugger.BusyEvaluatorDialog.cs +++ b/main/src/addins/MonoDevelop.Debugger/gtk-gui/MonoDevelop.Debugger.BusyEvaluatorDialog.cs @@ -56,7 +56,10 @@ namespace MonoDevelop.Debugger this.labelMethod = new global::Gtk.Label (); this.labelMethod.Name = "labelMethod"; this.labelMethod.Xalign = 0F; - this.labelMethod.LabelProp = "<mehtod>"; + this.labelMethod.LabelProp = "<method>"; + this.labelMethod.Wrap = true; + this.labelMethod.Selectable = true; + this.labelMethod.MaxWidthChars = 120; this.hbox1.Add (this.labelMethod); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.labelMethod])); w4.Position = 1; diff --git a/main/src/addins/MonoDevelop.Debugger/gtk-gui/gui.stetic b/main/src/addins/MonoDevelop.Debugger/gtk-gui/gui.stetic index 0516e36cc0..009262703f 100644 --- a/main/src/addins/MonoDevelop.Debugger/gtk-gui/gui.stetic +++ b/main/src/addins/MonoDevelop.Debugger/gtk-gui/gui.stetic @@ -336,7 +336,10 @@ <widget class="Gtk.Label" id="labelMethod"> <property name="MemberName" /> <property name="Xalign">0</property> - <property name="LabelProp"><mehtod></property> + <property name="LabelProp"><method></property> + <property name="Wrap">True</property> + <property name="Selectable">True</property> + <property name="MaxWidthChars">120</property> </widget> <packing> <property name="Position">1</property> diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/ComponentNodeBuilder.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/ComponentNodeBuilder.cs index 2505bd214e..eec13371ac 100644 --- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/ComponentNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/ComponentNodeBuilder.cs @@ -42,9 +42,9 @@ namespace MonoDevelop.DesignerSupport.Projects // Don't use the CurrentNode property here since it may not be properly initialized when the event is fired. ITreeNavigator nav = Tree.GetNodeAtObject (obj); if (nav != null) { - IWorkspaceFileObject ce = (IWorkspaceFileObject) nav.GetParentDataItem (typeof(IWorkspaceFileObject), true); + var ce = nav.GetParentDataItem<WorkspaceObject> (true); if (ce != null) { - IdeApp.ProjectOperations.Save (ce); + IdeApp.ProjectOperations.SaveAsync (ce); return; } } diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/PropertyPadTextEditorExtension.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/PropertyPadTextEditorExtension.cs index d97b8c2284..f4e140d29e 100644 --- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/PropertyPadTextEditorExtension.cs +++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/PropertyPadTextEditorExtension.cs @@ -62,7 +62,7 @@ namespace MonoDevelop.DesignerSupport.Projects public void OnChanged (object obj) { if (Document.HasProject) - IdeApp.ProjectOperations.Save (Document.Project); + IdeApp.ProjectOperations.SaveAsync (Document.Project); } } } diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemDescriptor.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemDescriptor.cs index 95721e4e71..d4f6d500fa 100644 --- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemDescriptor.cs +++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemDescriptor.cs @@ -33,9 +33,9 @@ namespace MonoDevelop.DesignerSupport.Projects { class SolutionItemDescriptor: CustomDescriptor { - SolutionItem entry; + SolutionFolderItem entry; - public SolutionItemDescriptor (SolutionItem entry) + public SolutionItemDescriptor (SolutionFolderItem entry) { this.entry = entry; } @@ -58,8 +58,8 @@ namespace MonoDevelop.DesignerSupport.Projects [LocalizedDescription ("File path of the solution item.")] public string FilePath { get { - if (entry is SolutionEntityItem) - return ((SolutionEntityItem) entry).FileName; + if (entry is SolutionItem) + return ((SolutionItem) entry).FileName; else return ""; } diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemPropertyProvider.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemPropertyProvider.cs index bfa8ea1faf..2753614d1a 100644 --- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemPropertyProvider.cs +++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Projects/SolutionItemPropertyProvider.cs @@ -38,12 +38,12 @@ namespace MonoDevelop.DesignerSupport.Projects if (obj is WorkspaceItem) return new WorkspaceItemDescriptor ((WorkspaceItem)obj); else - return new SolutionItemDescriptor ((SolutionItem)obj); + return new SolutionItemDescriptor ((SolutionFolderItem)obj); } public bool SupportsObject (object obj) { - return obj is SolutionItem || obj is WorkspaceItem; + return obj is SolutionFolderItem || obj is WorkspaceItem; } } } diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Toolbox/ComponentSelectorDialog.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Toolbox/ComponentSelectorDialog.cs index a257f5a9ca..153d62b0dd 100644 --- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Toolbox/ComponentSelectorDialog.cs +++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport.Toolbox/ComponentSelectorDialog.cs @@ -57,7 +57,7 @@ namespace MonoDevelop.DesignerSupport.Toolbox public ComponentSelectorDialog (IToolboxConsumer currentConsumer) { - using (IProgressMonitor monitor = new MessageDialogProgressMonitor (true, true, false, true)) { + using (ProgressMonitor monitor = new MessageDialogProgressMonitor (true, true, false, true)) { index = DesignerSupport.Service.ToolboxService.GetComponentIndex (monitor); } diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/CodeBehindWriter.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/CodeBehindWriter.cs index 44d2c1bc8f..891b6377e9 100644 --- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/CodeBehindWriter.cs +++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/CodeBehindWriter.cs @@ -44,7 +44,7 @@ namespace MonoDevelop.DesignerSupport List<KeyValuePair<FilePath,string>> filesToWrite = new List<KeyValuePair<FilePath,string>> (); CodeDomProvider provider; CodeGeneratorOptions options; - IProgressMonitor monitor; + ProgressMonitor monitor; public CodeDomProvider Provider { get { return provider; } } public CodeGeneratorOptions GeneratorOptions { get { return options; } } @@ -59,14 +59,14 @@ namespace MonoDevelop.DesignerSupport { } - CodeBehindWriter (IProgressMonitor monitor, CodeDomProvider provider, CodeGeneratorOptions options) + CodeBehindWriter (ProgressMonitor monitor, CodeDomProvider provider, CodeGeneratorOptions options) { this.provider = provider; this.options = options; this.monitor = monitor; } - public static CodeBehindWriter CreateForProject (IProgressMonitor monitor, DotNetProject project) + public static CodeBehindWriter CreateForProject (ProgressMonitor monitor, DotNetProject project) { var pol = project.Policies.Get<TextStylePolicy> (); var options = new CodeGeneratorOptions () { diff --git a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/ToolboxService.cs b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/ToolboxService.cs index 2c9c66e956..0c5cf4194e 100644 --- a/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/ToolboxService.cs +++ b/main/src/addins/MonoDevelop.DesignerSupport/MonoDevelop.DesignerSupport/ToolboxService.cs @@ -545,7 +545,7 @@ namespace MonoDevelop.DesignerSupport throw new InvalidOperationException ("Unexpected ToolboxItemFilterType value."); } - internal ComponentIndex GetComponentIndex (IProgressMonitor monitor) + internal ComponentIndex GetComponentIndex (ProgressMonitor monitor) { // Returns an index of all components that can be added to the toolbox. @@ -562,7 +562,7 @@ namespace MonoDevelop.DesignerSupport todelete.Add (ia); if (ia.NeedsUpdate) toupdate.Add (ia); - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) return index; } @@ -575,7 +575,7 @@ namespace MonoDevelop.DesignerSupport index.Files.Add (c); toupdate.Add (c); } - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) return index; } } @@ -591,7 +591,7 @@ namespace MonoDevelop.DesignerSupport foreach (ComponentIndexFile ia in toupdate) { ia.Update (ctx); monitor.Step (1); - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) return index; } } finally { diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/GettextEditorDisplayBinding.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/GettextEditorDisplayBinding.cs index 9a7d402c95..a572e7b707 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/GettextEditorDisplayBinding.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/GettextEditorDisplayBinding.cs @@ -49,7 +49,7 @@ namespace MonoDevelop.Gettext public IViewContent CreateContent (FilePath filePath, string mimeType, Project project) { - foreach (TranslationProject tp in IdeApp.Workspace.GetAllSolutionItems<TranslationProject> ()) + foreach (TranslationProject tp in IdeApp.Workspace.GetAllItems<TranslationProject> ()) if (tp.BaseDirectory == Path.GetDirectoryName (filePath)) return new Editor.CatalogEditorView (tp, filePath); diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/POEditorWidget.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/POEditorWidget.cs index 45747f5bb0..c39a8e1ede 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/POEditorWidget.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.Editor/POEditorWidget.cs @@ -976,7 +976,7 @@ namespace MonoDevelop.Gettext base.OnDestroyed (); } #region Tasks - public class TranslationTask : Task + public class TranslationTask : UserTask { POEditorWidget widget; CatalogEntry entry; @@ -1000,7 +1000,7 @@ namespace MonoDevelop.Gettext TaskService.Errors.ClearByOwner (this); } - static bool CompareTasks (List<Task> list1, List<Task> list2) + static bool CompareTasks (List<UserTask> list1, List<UserTask> list2) { if (list1.Count != list2.Count) return false; @@ -1128,7 +1128,7 @@ namespace MonoDevelop.Gettext } - List<Task> currentTasks = new List<Task> (); + List<UserTask> currentTasks = new List<UserTask> (); BackgroundWorker updateTaskThread = null; @@ -1140,7 +1140,7 @@ namespace MonoDevelop.Gettext return; } - List<Task> tasks = new List<Task> (); + List<UserTask> tasks = new List<UserTask> (); try { foreach (CatalogEntryRule rule in rules) { foreach (CatalogEntry entry in catalog) { diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/ProjectFileNodeBuilderExtension.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/ProjectFileNodeBuilderExtension.cs index 4d051544cb..e87629a944 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/ProjectFileNodeBuilderExtension.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/ProjectFileNodeBuilderExtension.cs @@ -68,7 +68,7 @@ namespace MonoDevelop.Gettext.NodeBuilders } } - Set<SolutionEntityItem> projects = new Set<SolutionEntityItem> (); + Set<SolutionItem> projects = new Set<SolutionItem> (); foreach (ITreeNavigator node in CurrentNodes) { ProjectFile file = (ProjectFile) node.DataItem; @@ -80,7 +80,7 @@ namespace MonoDevelop.Gettext.NodeBuilders } } - IdeApp.ProjectOperations.Save (projects); + IdeApp.ProjectOperations.SaveAsync (projects); } [CommandUpdateHandler (Commands.ScanForTranslations)] diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationNodeBuilder.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationNodeBuilder.cs index 029efd19d4..a1d3c3aacd 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationNodeBuilder.cs @@ -33,6 +33,7 @@ using MonoDevelop.Core; using MonoDevelop.Components.Commands; using MonoDevelop.Ide.Gui.Components; using MonoDevelop.Ide; +using System.Threading.Tasks; namespace MonoDevelop.Gettext.NodeBuilders { @@ -111,7 +112,7 @@ namespace MonoDevelop.Gettext.NodeBuilders } project.RemoveTranslation (translation.IsoCode); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); } } @@ -125,14 +126,10 @@ namespace MonoDevelop.Gettext.NodeBuilders UpdateTranslations (project, translation); } - static IAsyncOperation currentUpdateTranslationOperation = MonoDevelop.Core.ProgressMonitoring.NullAsyncOperation.Success; + static Task currentUpdateTranslationOperation = Task.FromResult (0); - void UpdateTranslationsAsync (object ob) + void UpdateTranslationsAsync (ProgressMonitor monitor, TranslationProject project, Translation translation) { - object[] data = (object[]) ob; - IProgressMonitor monitor = (IProgressMonitor) data [0]; - TranslationProject project = (TranslationProject) data [1]; - Translation translation = (Translation) data [2]; try { project.UpdateTranslations (monitor, translation); Gtk.Application.Invoke (delegate { @@ -151,9 +148,8 @@ namespace MonoDevelop.Gettext.NodeBuilders { if (currentUpdateTranslationOperation != null && !currentUpdateTranslationOperation.IsCompleted) return; - IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor (); - currentUpdateTranslationOperation = monitor.AsyncOperation; - DispatchService.BackgroundDispatch (new StatefulMessageHandler (UpdateTranslationsAsync), new object[] {monitor, project, translation}); + ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor (); + currentUpdateTranslationOperation = Task.Factory.StartNew (() => UpdateTranslationsAsync (monitor, project, translation)); } } } diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationProjectNodeBuilder.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationProjectNodeBuilder.cs index cdfdc78f73..938ce3a94b 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationProjectNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext.NodeBuilders/TranslationProjectNodeBuilder.cs @@ -32,6 +32,7 @@ using MonoDevelop.Core; using MonoDevelop.Components.Commands; using MonoDevelop.Ide.Gui.Components; using MonoDevelop.Ide; +using System.Threading.Tasks; namespace MonoDevelop.Gettext.NodeBuilders { @@ -122,7 +123,7 @@ namespace MonoDevelop.Gettext.NodeBuilders if (project == null) return; MessageService.ShowCustomDialog (new TranslationProjectOptionsDialog (project)); - IdeApp.Workspace.Save (); + IdeApp.Workspace.SaveAsync (); } [CommandUpdateHandler (Commands.AddTranslation)] @@ -144,7 +145,7 @@ namespace MonoDevelop.Gettext.NodeBuilders if (MessageService.RunCustomDialog (chooser) == (int)ResponseType.Ok) { string language = chooser.Language + (chooser.HasCountry ? "_" + chooser.Country : ""); - using (IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor (monitorTitle, "md-package", true, true)) { + using (ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor (monitorTitle, "md-package", true, true)) { project.AddNewTranslation (language, monitor); UpdateTranslations (project); } @@ -154,14 +155,10 @@ namespace MonoDevelop.Gettext.NodeBuilders chooser.Destroy (); } } - static IAsyncOperation currentUpdateTranslationOperation = MonoDevelop.Core.ProgressMonitoring.NullAsyncOperation.Success; + static Task currentUpdateTranslationOperation = Task.FromResult (0); - void UpdateTranslationsAsync (object ob) + void UpdateTranslationsAsync (ProgressMonitor monitor, TranslationProject project) { - object[] data = (object[]) ob; - IProgressMonitor monitor = (IProgressMonitor) data [0]; - TranslationProject project = (TranslationProject) data [1]; - try { project.UpdateTranslations (monitor); Gtk.Application.Invoke (delegate { @@ -180,9 +177,8 @@ namespace MonoDevelop.Gettext.NodeBuilders { if (currentUpdateTranslationOperation != null && !currentUpdateTranslationOperation.IsCompleted) return; - IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor (); - currentUpdateTranslationOperation = monitor.AsyncOperation; - DispatchService.BackgroundDispatch (new StatefulMessageHandler (UpdateTranslationsAsync), new object[] {monitor, project}); + ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor (); + currentUpdateTranslationOperation = Task.Factory.StartNew (() => UpdateTranslationsAsync (monitor, project)); } [CommandHandler (Commands.UpdateTranslations)] diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Catalog.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Catalog.cs index a6322e961b..6171e5533f 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Catalog.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Catalog.cs @@ -201,7 +201,7 @@ namespace MonoDevelop.Gettext /// <summary> /// Loads catalog from .po file. /// </summary> - public bool Load (IProgressMonitor monitor, string poFile) + public bool Load (ProgressMonitor monitor, string poFile) { Clear (); isOk = false; @@ -439,7 +439,7 @@ namespace MonoDevelop.Gettext } // Updates the catalog from POT file. - public bool UpdateFromPOT (IProgressMonitor mon, string potFile, bool summary) + public bool UpdateFromPOT (ProgressMonitor mon, string potFile, bool summary) { if (! isOk) return false; @@ -685,7 +685,7 @@ namespace MonoDevelop.Gettext // (in the sense of msgmerge -- this catalog is old one with // translations, \a refcat is reference catalog created by Update().) // return true if the merge was successfull, false otherwise. - public bool Merge (IProgressMonitor mon, Catalog refCat) + public bool Merge (ProgressMonitor mon, Catalog refCat) { // TODO: implement via monitor, not in a GUI thread... // But mind about it as it would be used during build. diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeature.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeature.cs index acf0ff8cbe..b7f431b9cf 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeature.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeature.cs @@ -46,7 +46,7 @@ namespace MonoDevelop.Gettext get { return GettextCatalog.GetString ("Add a Translation Project to the solution that will use gettext to generate a set of PO files for the new project."); } } - public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionItem entry) + public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionFolderItem entry) { if (entry is TranslationProject && parentCombine != null) return FeatureSupportLevel.Enabled; @@ -56,22 +56,22 @@ namespace MonoDevelop.Gettext return FeatureSupportLevel.NotSupported; } - public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionItem entry) + public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionFolderItem entry) { return new GettextFeatureWidget (); } - public void ApplyFeature (SolutionFolder parentCombine, SolutionItem entry, Widget editor) + public void ApplyFeature (SolutionFolder parentCombine, SolutionFolderItem entry, Widget editor) { ((GettextFeatureWidget)editor).ApplyFeature (parentCombine, entry); } - public string Validate (SolutionFolder parentCombine, SolutionItem entry, Gtk.Widget editor) + public string Validate (SolutionFolder parentCombine, SolutionFolderItem entry, Gtk.Widget editor) { return null; } - public bool IsEnabled (SolutionFolder parentCombine, SolutionItem entry) + public bool IsEnabled (SolutionFolder parentCombine, SolutionFolderItem entry) { return entry is TranslationProject; } diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeatureWidget.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeatureWidget.cs index 130f9c5c8a..c103ee2939 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeatureWidget.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextFeatureWidget.cs @@ -31,7 +31,7 @@ using Gtk; using MonoDevelop.Projects; using MonoDevelop.Gettext.Translator; -using MonoDevelop.Core.ProgressMonitoring; +using MonoDevelop.Core; using MonoDevelop.Ide; namespace MonoDevelop.Gettext @@ -74,7 +74,7 @@ namespace MonoDevelop.Gettext }; } - public void ApplyFeature (SolutionFolder parentCombine, SolutionItem entry) + public void ApplyFeature (SolutionFolder parentCombine, SolutionFolderItem entry) { TranslationProject newProject; if (entry is TranslationProject) @@ -93,7 +93,7 @@ namespace MonoDevelop.Gettext if (store.GetIterFirst (out iter)) { do { string code = (string)store.GetValue (iter, 1); - newProject.AddNewTranslation (code, new NullProgressMonitor ()); + newProject.AddNewTranslation (code, new ProgressMonitor ()); } while (store.IterNext (ref iter)); } } diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextTool.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextTool.cs index 96bf769a7a..b530133bc6 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextTool.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/GettextTool.cs @@ -74,7 +74,7 @@ namespace MonoDevelop.Gettext ConsoleProgressMonitor monitor = new ConsoleProgressMonitor (); monitor.IgnoreLogMessages = true; - WorkspaceItem centry = Services.ProjectService.ReadWorkspaceItem (monitor, file); + WorkspaceItem centry = Services.ProjectService.ReadWorkspaceItem (monitor, file).Result; monitor.IgnoreLogMessages = false; Solution solution = centry as Solution; @@ -84,7 +84,7 @@ namespace MonoDevelop.Gettext } if (project != null) { - SolutionEntityItem item = solution.FindProjectByName (project); + SolutionItem item = solution.FindProjectByName (project); if (item == null) { Console.WriteLine ("The project '" + project + "' could not be found in " + file); @@ -98,7 +98,7 @@ namespace MonoDevelop.Gettext tp.UpdateTranslations (monitor); } else { - foreach (TranslationProject p in solution.GetAllSolutionItems <TranslationProject>()) + foreach (TranslationProject p in solution.GetAllItems <TranslationProject>()) p.UpdateTranslations (monitor); } diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/IFileScanner.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/IFileScanner.cs index 3f722b7b16..fabcabb70e 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/IFileScanner.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/IFileScanner.cs @@ -33,6 +33,6 @@ namespace MonoDevelop.Gettext interface IFileScanner { bool CanScan (TranslationProject project, Catalog catalog, string fileName, string mimeType); - void UpdateCatalog (TranslationProject project, Catalog catalog, IProgressMonitor monitor, string fileName); + void UpdateCatalog (TranslationProject project, Catalog catalog, ProgressMonitor monitor, string fileName); } } diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/MakefileHandler.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/MakefileHandler.cs index baca1511d0..72ddc7c24e 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/MakefileHandler.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/MakefileHandler.cs @@ -39,12 +39,12 @@ namespace MonoDevelop.Gettext { class MakefileHandler: IMakefileHandler { - public bool CanDeploy (SolutionItem entry, MakefileType type) + public bool CanDeploy (SolutionFolderItem entry, MakefileType type) { return entry is TranslationProject; } - public Makefile Deploy (AutotoolsContext ctx, SolutionItem entry, IProgressMonitor monitor) + public Makefile Deploy (AutotoolsContext ctx, SolutionFolderItem entry, ProgressMonitor monitor) { Makefile mkfile = new Makefile (); TranslationProject project = (TranslationProject) entry; diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/RegexFileScanner.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/RegexFileScanner.cs index 0e84bc1ee1..144d1b69c1 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/RegexFileScanner.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/RegexFileScanner.cs @@ -118,7 +118,7 @@ namespace MonoDevelop.Gettext return r; } - public virtual void UpdateCatalog (TranslationProject project, Catalog catalog, IProgressMonitor monitor, string fileName) + public virtual void UpdateCatalog (TranslationProject project, Catalog catalog, ProgressMonitor monitor, string fileName) { string text = File.ReadAllText (fileName); string relativeFileName = MonoDevelop.Core.FileService.AbsoluteToRelativePath (project.BaseDirectory, fileName); diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Translation.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Translation.cs index 84a8ecf5cd..178a069000 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Translation.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/Translation.cs @@ -84,7 +84,7 @@ namespace MonoDevelop.Gettext return Path.Combine (moDirectory, parentProject.PackageName + ".mo"); } - public BuildResult Build (IProgressMonitor monitor, ConfigurationSelector configuration) + public BuildResult Build (ProgressMonitor monitor, ConfigurationSelector configuration) { BuildResult results = new BuildResult ("", 0, 0); diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProject.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProject.cs index fcef46a792..d77a23bcc8 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProject.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProject.cs @@ -38,10 +38,12 @@ using MonoDevelop.Core.Serialization; using MonoDevelop.Deployment; using MonoDevelop.Ide; using MonoDevelop.Core.Execution; +using System.Linq; +using System.Threading.Tasks; namespace MonoDevelop.Gettext { - class TranslationProject : SolutionEntityItem, IDeployable + class TranslationProject : SolutionItem, IDeployable { [ItemProperty("packageName")] string packageName = null; @@ -94,9 +96,9 @@ namespace MonoDevelop.Gettext Configurations.Add (new TranslationProjectConfiguration (config)); } - protected override List<FilePath> OnGetItemFiles (bool includeReferencedFiles) + protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) {
- List<FilePath> col = base.OnGetItemFiles (includeReferencedFiles); + List<FilePath> col = base.OnGetItemFiles (includeReferencedFiles).ToList(); if (includeReferencedFiles) { foreach (Translation tr in translations) col.Add (tr.PoFile); @@ -104,7 +106,7 @@ namespace MonoDevelop.Gettext return col; } - public TranslationProjectInformation GetProjectInformation (SolutionItem entry, bool force) + public TranslationProjectInformation GetProjectInformation (SolutionFolderItem entry, bool force) { foreach (TranslationProjectInformation info in this.projectInformations) { if (info.ProjectName == entry.Name) @@ -118,7 +120,7 @@ namespace MonoDevelop.Gettext return null; } - public bool IsIncluded (SolutionItem entry) + public bool IsIncluded (SolutionFolderItem entry) { TranslationProjectInformation info = GetProjectInformation (entry, false); if (info != null) @@ -126,7 +128,7 @@ namespace MonoDevelop.Gettext return true; } - public override void InitializeFromTemplate (XmlElement template) + protected override void OnInitializeFromTemplate (XmlElement template) { OutputType = (TranslationOutputType)Enum.Parse (typeof(TranslationOutputType), template.GetAttribute ("outputType")); PackageName = template.GetAttribute ("packageName"); @@ -169,7 +171,7 @@ namespace MonoDevelop.Gettext } - public Translation AddNewTranslation (string isoCode, IProgressMonitor monitor) + public Translation AddNewTranslation (string isoCode, ProgressMonitor monitor) { try { Translation tr = new Translation (this, isoCode); @@ -236,7 +238,7 @@ namespace MonoDevelop.Gettext return Path.Combine (this.ParentSolution.StartupItem.BaseDirectory, RelPath); } - void CreateDefaultCatalog (IProgressMonitor monitor) + void CreateDefaultCatalog (ProgressMonitor monitor) { IFileScanner[] scanners = TranslationService.GetFileScanners (); @@ -259,19 +261,19 @@ namespace MonoDevelop.Gettext } } } - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) return; monitor.Step (1); } catalog.Save (Path.Combine (this.BaseDirectory, "messages.po")); } - public void UpdateTranslations (IProgressMonitor monitor) + public void UpdateTranslations (ProgressMonitor monitor) { UpdateTranslations (monitor, translations.ToArray ()); } - public void UpdateTranslations (IProgressMonitor monitor, params Translation[] translations) + public void UpdateTranslations (ProgressMonitor monitor, params Translation[] translations) { monitor.BeginTask (null, Translations.Count + 1); @@ -288,7 +290,7 @@ namespace MonoDevelop.Gettext monitor.EndTask (); monitor.Step (1); } - if (monitor.IsCancelRequested) { + if (monitor.CancellationToken.IsCancellationRequested) { monitor.Log.WriteLine (GettextCatalog.GetString ("Operation cancelled.")); return; } @@ -324,7 +326,7 @@ namespace MonoDevelop.Gettext monitor.EndTask (); monitor.Step (1); } - if (monitor.IsCancelRequested) { + if (monitor.CancellationToken.IsCancellationRequested) { monitor.Log.WriteLine (GettextCatalog.GetString ("Operation cancelled.")); return; } @@ -335,7 +337,7 @@ namespace MonoDevelop.Gettext foreach (Translation translation in this.Translations) { string poFileName = translation.PoFile; Catalog catalog = new Catalog (this); - catalog.Load (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), poFileName); + catalog.Load (new MonoDevelop.Core.ProgressMonitor (), poFileName); CatalogEntry entry = catalog.FindItem (msgstr); if (entry != null) { catalog.RemoveItem (entry); @@ -344,40 +346,43 @@ namespace MonoDevelop.Gettext } } - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected async override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { + var toBuild = Translations.Where (t => t.NeedsBuilding(configuration)).ToArray (); BuildResult results = new BuildResult ("", 1, 0); string outputDirectory = GetOutputDirectory (configuration); if (!string.IsNullOrEmpty (outputDirectory)) { - foreach (Translation translation in this.Translations) { - if (translation.NeedsBuilding (configuration)) { - BuildResult res = translation.Build (monitor, configuration); - results.Append (res); + await Task.Factory.StartNew (delegate { + foreach (Translation translation in toBuild) { + if (translation.NeedsBuilding (configuration)) { + BuildResult res = translation.Build (monitor, configuration); + results.Append (res); + } } - } - isDirty = false; + isDirty = false; + }); } return results; } - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) + protected async override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) { isDirty = true; monitor.Log.WriteLine (GettextCatalog.GetString ("Removing all .mo files.")); string outputDirectory = GetOutputDirectory (configuration); if (string.IsNullOrEmpty (outputDirectory)) - return; - foreach (Translation translation in this.Translations) { - string moFileName = translation.GetOutFile (configuration); - if (File.Exists (moFileName)) - File.Delete (moFileName); - } - } - - protected override void OnExecute (IProgressMonitor monitor, MonoDevelop.Projects.ExecutionContext context, ConfigurationSelector configuration) - { + return BuildResult.Success; + + var toClean = Translations.Select (t => t.GetOutFile (configuration)).ToArray (); + await Task.Factory.StartNew (delegate { + foreach (string moFileName in toClean) { + if (File.Exists (moFileName)) + File.Delete (moFileName); + } + }); + return BuildResult.Success; } - + #region Deployment public DeployFileCollection GetDeployFiles (ConfigurationSelector configuration) { @@ -410,11 +415,6 @@ namespace MonoDevelop.Gettext return false; } - protected override void OnSetNeedsBuilding (bool val, ConfigurationSelector configuration) - { - isDirty = val; - } - protected virtual void OnTranslationAdded (EventArgs e) { if (TranslationAdded != null) diff --git a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProjectOptionsDialog.cs b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProjectOptionsDialog.cs index 185e521dc7..b1199da866 100644 --- a/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProjectOptionsDialog.cs +++ b/main/src/addins/MonoDevelop.Gettext/MonoDevelop.Gettext/TranslationProjectOptionsDialog.cs @@ -67,7 +67,7 @@ namespace MonoDevelop.Gettext this.Destroy (); }; - store = new TreeStore (typeof(string), typeof(bool), typeof(string), typeof(SolutionItem), typeof(bool)); + store = new TreeStore (typeof(string), typeof(bool), typeof(string), typeof(SolutionFolderItem), typeof(bool)); treeviewProjectList.Model = store; treeviewProjectList.HeadersVisible = false; @@ -98,7 +98,7 @@ namespace MonoDevelop.Gettext TreeIter iter; if (store.GetIterFromString (out iter, e.Path)) { bool isTogglod = (bool)store.GetValue (iter, 1); - SolutionItem entry = (SolutionItem)store.GetValue (iter, 3); + SolutionFolderItem entry = (SolutionFolderItem)store.GetValue (iter, 3); if (entry is Project) { TranslationProjectInformation info = project.GetProjectInformation (entry, true); info.IsIncluded = !isTogglod; @@ -108,7 +108,7 @@ namespace MonoDevelop.Gettext } TreeStore store; - string GetIcon (SolutionItem entry) + string GetIcon (SolutionFolderItem entry) { if (entry is SolutionFolder) return MonoDevelop.Ide.Gui.Stock.Solution; @@ -119,10 +119,10 @@ namespace MonoDevelop.Gettext return MonoDevelop.Ide.Gui.Stock.Project; } - bool IsIncluded (SolutionItem entry) + bool IsIncluded (SolutionFolderItem entry) { if (entry is SolutionFolder) { - foreach (SolutionItem childEntry in ((SolutionFolder)entry).Items) + foreach (SolutionFolderItem childEntry in ((SolutionFolder)entry).Items) if (!IsIncluded (childEntry)) return false; return true; @@ -134,7 +134,7 @@ namespace MonoDevelop.Gettext return true; } - void FillTree (TreeIter iter, SolutionItem entry) + void FillTree (TreeIter iter, SolutionFolderItem entry) { TreeIter curIter; if (!iter.Equals (TreeIter.Zero)) { @@ -144,10 +144,10 @@ namespace MonoDevelop.Gettext } if (entry is SolutionFolder) { // Add solutions first, then projects - foreach (SolutionItem childEntry in ((SolutionFolder)entry).Items) + foreach (SolutionFolderItem childEntry in ((SolutionFolder)entry).Items) if (childEntry is SolutionFolder) FillTree (curIter, childEntry); - foreach (SolutionItem childEntry in ((SolutionFolder)entry).Items) + foreach (SolutionFolderItem childEntry in ((SolutionFolder)entry).Items) if (!(childEntry is TranslationProject) && (childEntry is Project)) FillTree (curIter, childEntry); } diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.Dialogs/GtkFeatureWidget.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.Dialogs/GtkFeatureWidget.cs index 0b6e913dc9..1496e4cba0 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.Dialogs/GtkFeatureWidget.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.Dialogs/GtkFeatureWidget.cs @@ -48,7 +48,7 @@ namespace MonoDevelop.GtkCore.Dialogs get { return GettextCatalog.GetString ("Enables support for GTK# in the project. Allows the visual design of GTK# windows, and the creation of a GTK# widget library."); } } - public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionItem entry) + public FeatureSupportLevel GetSupportLevel (SolutionFolder parentCombine, SolutionFolderItem entry) { if (!(entry is DotNetProject) || !GtkDesignInfo.SupportsRefactoring (entry as DotNetProject)) return FeatureSupportLevel.NotSupported; @@ -59,18 +59,18 @@ namespace MonoDevelop.GtkCore.Dialogs if (GtkDesignInfo.SupportsDesigner ((Project)entry)) return FeatureSupportLevel.Enabled; - else if (entry is DotNetAssemblyProject) + else if (entry is DotNetProject) return FeatureSupportLevel.SupportedByDefault; else return FeatureSupportLevel.Supported; } - public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionItem entry) + public Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionFolderItem entry) { return new GtkFeatureWidget ((DotNetProject) entry); } - public void ApplyFeature (SolutionFolder parentCombine, SolutionItem entry, Widget editor) + public void ApplyFeature (SolutionFolder parentCombine, SolutionFolderItem entry, Widget editor) { GtkFeatureWidget fw = (GtkFeatureWidget) editor; ReferenceManager refmgr = new ReferenceManager ((DotNetProject) entry); @@ -78,7 +78,7 @@ namespace MonoDevelop.GtkCore.Dialogs refmgr.Dispose (); } - public string Validate (SolutionFolder parentCombine, SolutionItem entry, Gtk.Widget editor) + public string Validate (SolutionFolder parentCombine, SolutionFolderItem entry, Gtk.Widget editor) { return null; } diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GtkProjectServiceExtension.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GtkProjectServiceExtension.cs index 191037ecd8..35cbbfb921 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GtkProjectServiceExtension.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GtkProjectServiceExtension.cs @@ -4,12 +4,13 @@ using System.Threading; using MonoDevelop.Core; using MonoDevelop.Projects; using MonoDevelop.Ide; +using System.Threading.Tasks; namespace MonoDevelop.GtkCore.GuiBuilder { - public class GtkProjectServiceExtension: ProjectServiceExtension + public class GtkProjectServiceExtension: DotNetProjectExtension { - public override bool SupportsItem (IBuildTarget item) + protected override bool SupportsObject (WorkspaceObject item) { if (!IdeApp.IsInitialized) return false; @@ -18,20 +19,19 @@ namespace MonoDevelop.GtkCore.GuiBuilder return project != null && GtkDesignInfo.HasDesignedObjects (project); } - protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) + protected async override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { - DotNetProject project = (DotNetProject) entry; - GtkDesignInfo info = GtkDesignInfo.FromProject (project); + GtkDesignInfo info = GtkDesignInfo.FromProject (Project); - // The code generator must run in the GUI thread since it needs to - // access to Gtk classes Generator gen = new Generator (); - lock (gen) { - Gtk.Application.Invoke (delegate { gen.Run (monitor, project, configuration); }); - Monitor.Wait (gen); + if (!await gen.Run (monitor, Project, configuration)) { + BuildResult gr = new BuildResult (); + foreach (string s in gen.Messages) + gr.AddError (info.GuiBuilderProject.File, 0, 0, null, s); + return gr; } - BuildResult res = base.Build (monitor, entry, configuration); + BuildResult res = await base.OnBuild (monitor, configuration); if (gen.Messages != null) { foreach (string s in gen.Messages) @@ -43,7 +43,7 @@ namespace MonoDevelop.GtkCore.GuiBuilder if (res.Failed && !Platform.IsWindows && !Platform.IsMac) { // Some gtk# packages don't include the .pc file unless you install gtk-sharp-devel - if (project.AssemblyContext.GetPackage ("gtk-sharp-2.0") == null) { + if (Project.AssemblyContext.GetPackage ("gtk-sharp-2.0") == null) { string msg = GettextCatalog.GetString ( "ERROR: MonoDevelop could not find the Gtk# 2.0 development package. " + "Compilation of projects depending on Gtk# libraries will fail. " + @@ -59,19 +59,22 @@ namespace MonoDevelop.GtkCore.GuiBuilder class Generator { - public void Run (IProgressMonitor monitor, DotNetProject project, ConfigurationSelector configuration) + public async Task<bool> Run (ProgressMonitor monitor, DotNetProject project, ConfigurationSelector configuration) { - lock (this) { - try { - Stetic.CodeGenerationResult res = GuiBuilderService.GenerateSteticCode (monitor, project, configuration); - if (res != null) - Messages = res.Warnings; - } catch (Exception ex) { - Error = ex; - LoggingService.LogError (ex.ToString ()); - Messages = new string [] { Error.Message }; + try { + Stetic.CodeGenerationResult res = await GuiBuilderService.GenerateSteticCode (monitor, project, configuration); + if (res != null) { + Messages = res.Warnings; + return true; + } else { + Messages = new [] { GettextCatalog.GetString ("Code generation failed") }; + return false; } - Monitor.PulseAll (this); + } catch (Exception ex) { + Error = ex; + LoggingService.LogError (ex.ToString ()); + Messages = new [] { Error.Message }; + return false; } } public string[] Messages; diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderProject.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderProject.cs index 6a23250d36..9c381c600d 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderProject.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderProject.cs @@ -219,7 +219,7 @@ namespace MonoDevelop.GtkCore.GuiBuilder } if (GtkDesignInfo.FromProject (project).UpdateGtkFolder () && saveMdProject) - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); } public string File { diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderService.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderService.cs index 28dac4d37e..601733e9d3 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderService.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.GuiBuilder/GuiBuilderService.cs @@ -42,6 +42,7 @@ using MonoDevelop.Projects.Policies; using MonoDevelop.Ide; using MonoDevelop.Ide.Gui.Content; using MonoDevelop.Ide.TypeSystem; +using System.Threading.Tasks; namespace MonoDevelop.GtkCore.GuiBuilder @@ -385,7 +386,7 @@ namespace MonoDevelop.GtkCore.GuiBuilder } - public static Stetic.CodeGenerationResult GenerateSteticCode (IProgressMonitor monitor, DotNetProject project, ConfigurationSelector configuration) + public async static Task<Stetic.CodeGenerationResult> GenerateSteticCode (ProgressMonitor monitor, DotNetProject project, ConfigurationSelector configuration) { if (generating || !GtkDesignInfo.HasDesignedObjects (project)) return null; @@ -423,7 +424,6 @@ namespace MonoDevelop.GtkCore.GuiBuilder if (info.GuiBuilderProject.HasError) { monitor.ReportError (GettextCatalog.GetString ("GUI code generation failed for project '{0}'. The file '{1}' could not be loaded.", project.Name, info.SteticFile), null); - monitor.AsyncOperation.Cancel (); return null; } @@ -454,8 +454,7 @@ namespace MonoDevelop.GtkCore.GuiBuilder if (!canGenerateInProcess) { timer.Trace ("Generating out of process"); - // Run the generation in another thread to avoid freezing the GUI - System.Threading.ThreadPool.QueueUserWorkItem (delegate { + await Task.Factory.StartNew (delegate { try { // Generate the code in another process if stetic is not isolated CodeGeneratorProcess cob = (CodeGeneratorProcess)Runtime.ProcessService.CreateExternalProcessObject (typeof(CodeGeneratorProcess), false); @@ -469,10 +468,6 @@ namespace MonoDevelop.GtkCore.GuiBuilder } }); - while (generating) { - DispatchService.RunPendingEvents (); - System.Threading.Thread.Sleep (100); - } } else { timer.Trace ("Generating in-process"); // No need to create another process, since stetic has its own backend process @@ -544,7 +539,7 @@ namespace MonoDevelop.GtkCore.GuiBuilder // Make sure the generated files are added to the project if (info.UpdateGtkFolder ()) { Gtk.Application.Invoke (delegate { - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); }); } diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ActionGroupNodeBuilder.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ActionGroupNodeBuilder.cs index b83e9e7a11..5b0fd87a2f 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ActionGroupNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ActionGroupNodeBuilder.cs @@ -136,7 +136,7 @@ namespace MonoDevelop.GtkCore.NodeBuilders } gproject.RemoveActionGroup (group); gproject.SaveProject (false); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); } } } diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ProjectFolderNodeBuilderExtension.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ProjectFolderNodeBuilderExtension.cs index 59c1529d1a..42cfbd603d 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ProjectFolderNodeBuilderExtension.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/ProjectFolderNodeBuilderExtension.cs @@ -182,7 +182,7 @@ namespace MonoDevelop.GtkCore.NodeBuilders IdeApp.ProjectOperations.CreateProjectFile (project, path, id); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); ITreeNavigator nav = Tree.GetNodeAtObject (dataItem); if (nav != null) diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/WidgetNodeBuilder.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/WidgetNodeBuilder.cs index 79e0b00d81..c0d692977c 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/WidgetNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.NodeBuilders/WidgetNodeBuilder.cs @@ -141,7 +141,7 @@ namespace MonoDevelop.GtkCore.NodeBuilders } w.Project.Remove (w); w.Project.SaveProject (false); - IdeApp.ProjectOperations.Save (w.Project.Project); + IdeApp.ProjectOperations.SaveAsync (w.Project.Project); } } } diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.addin.xml b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.addin.xml index 8cf80f0493..a892ef2a5b 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.addin.xml +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore.addin.xml @@ -146,8 +146,8 @@ <StockIcon stockid = "md-gtkcore-actiongroup" resource = "actiongroup.png" /> </Extension> - <Extension path = "/MonoDevelop/ProjectModel/ProjectServiceExtensions"> - <Class class = "MonoDevelop.GtkCore.GuiBuilder.GtkProjectServiceExtension" insertafter="MidStep"/> + <Extension path = "/MonoDevelop/ProjectModel/ProjectModelExtensions"> + <ProjectExtension class = "MonoDevelop.GtkCore.GuiBuilder.GtkProjectServiceExtension" insertafter="MidStep"/> </Extension> <Extension path = "/MonoDevelop/DesignerSupport/ToolboxProviders"> diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/ProjectResourceProvider.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/ProjectResourceProvider.cs index e1c46517d8..6128a6a9bf 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/ProjectResourceProvider.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/ProjectResourceProvider.cs @@ -65,7 +65,7 @@ namespace MonoDevelop.GtkCore public Stetic.ResourceInfo AddResource (string fileName) { ProjectFile file = project.AddFile (fileName, BuildAction.EmbeddedResource); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); return new Stetic.ResourceInfo (file.ResourceId, fileName); } @@ -74,7 +74,7 @@ namespace MonoDevelop.GtkCore foreach (ProjectFile file in project.Files) { if (resourceName == file.ResourceId) { project.Files.Remove (file); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); return; } } diff --git a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/WidgetFileDescriptionTemplate.cs b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/WidgetFileDescriptionTemplate.cs index 68161a0a33..e9642c0d0e 100644 --- a/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/WidgetFileDescriptionTemplate.cs +++ b/main/src/addins/MonoDevelop.GtkCore/MonoDevelop.GtkCore/WidgetFileDescriptionTemplate.cs @@ -77,7 +77,7 @@ namespace MonoDevelop.GtkCore return (project is DotNetProject) && GtkDesignInfo.SupportsRefactoring (project as DotNetProject); } - public override bool AddToProject (SolutionItem policyParent, Project project, string language, string directory, string name) + public override bool AddToProject (SolutionFolderItem policyParent, Project project, string language, string directory, string name) { if (!GtkDesignInfo.SupportsDesigner (project)) { ReferenceManager mgr = new ReferenceManager (project as DotNetProject); @@ -114,7 +114,7 @@ namespace MonoDevelop.GtkCore gproject.AddNewComponent (doc.DocumentElement); gproject.SaveAll (false); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); return true; } @@ -128,7 +128,7 @@ namespace MonoDevelop.GtkCore gproject.SteticProject.AddNewActionGroup (doc.DocumentElement); gproject.SaveAll (false); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); return true; } diff --git a/main/src/addins/MonoDevelop.GtkCore/libstetic/ImageInfo.cs b/main/src/addins/MonoDevelop.GtkCore/libstetic/ImageInfo.cs index 90e6e17c7b..0a766731d3 100644 --- a/main/src/addins/MonoDevelop.GtkCore/libstetic/ImageInfo.cs +++ b/main/src/addins/MonoDevelop.GtkCore/libstetic/ImageInfo.cs @@ -117,6 +117,8 @@ namespace Stetic } catch { // Not a valid image return WidgetUtils.MissingIcon; + } finally { + s.Dispose (); } case ImageSource.Theme: diff --git a/main/src/addins/MonoDevelop.GtkCore/libstetic/editor/SelectImageDialog.cs b/main/src/addins/MonoDevelop.GtkCore/libstetic/editor/SelectImageDialog.cs index 3f64c92369..c4f6330cb6 100644 --- a/main/src/addins/MonoDevelop.GtkCore/libstetic/editor/SelectImageDialog.cs +++ b/main/src/addins/MonoDevelop.GtkCore/libstetic/editor/SelectImageDialog.cs @@ -207,13 +207,14 @@ namespace Stetic.Editor { try { Gdk.Pixbuf pix = new Gdk.Pixbuf (stream); - stream.Close (); string txt = name + "\n<span foreground='darkgrey' size='x-small'>" + pix.Width + " x " + pix.Height + "</span>"; pix = GetThumbnail (pix); resourceListStore.AppendValues (pix, txt, name); resources [name] = pix; } catch { // Doesn't look like a valid image. Just ignore it. + } finally { + stream.Dispose (); } } diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ButtonFunction.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ButtonFunction.cs deleted file mode 100644 index 9fa8ef4907..0000000000 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ButtonFunction.cs +++ /dev/null @@ -1,20 +0,0 @@ -// This file was generated by the Gtk# code generator. -// Any changes made will be lost if regenerated. - -namespace Stetic.Metacity -{ - - using System; - using System.Runtime.InteropServices; - -#region Autogenerated code - internal enum ButtonFunction { - - Menu, - Minimize, - Maximize, - Close, - Last, - } -#endregion -} diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ButtonLayout.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ButtonLayout.cs deleted file mode 100644 index e954c20a3e..0000000000 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ButtonLayout.cs +++ /dev/null @@ -1,36 +0,0 @@ -// This file was generated by the Gtk# code generator. -// Any changes made will be lost if regenerated. - -namespace Stetic.Metacity -{ - - using System; - using System.Collections; - using System.Runtime.InteropServices; - -#region Autogenerated code - [StructLayout(LayoutKind.Sequential)] - internal struct ButtonLayout { - - [MarshalAs (UnmanagedType.ByValArray, SizeConst=4)] - public Metacity.ButtonFunction[] LeftButtons; - [MarshalAs (UnmanagedType.ByValArray, SizeConst=4)] - public Metacity.ButtonFunction[] RightButtons; - - public static Metacity.ButtonLayout Zero = new Metacity.ButtonLayout (); - - public static Metacity.ButtonLayout New(IntPtr raw) { - if (raw == IntPtr.Zero) { - return Metacity.ButtonLayout.Zero; - } - Metacity.ButtonLayout self = new Metacity.ButtonLayout(); - self = (Metacity.ButtonLayout) Marshal.PtrToStructure (raw, self.GetType ()); - return self; - } - - internal static GLib.GType GType { - get { return GLib.GType.Pointer; } - } -#endregion - } -} diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/FrameFlags.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/FrameFlags.cs deleted file mode 100644 index bc6172fbe8..0000000000 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/FrameFlags.cs +++ /dev/null @@ -1,30 +0,0 @@ -// This file was generated by the Gtk# code generator. -// Any changes made will be lost if regenerated. - -namespace Stetic.Metacity -{ - - using System; - using System.Runtime.InteropServices; - -#region Autogenerated code - [Flags] - internal enum FrameFlags { - - AllowsDelete = 1 << 0, - AllowsMenu = 1 << 1, - AllowsMinimize = 1 << 2, - AllowsMaximize = 1 << 3, - AllowsVerticalResize = 1 << 4, - AllowsHorizontalResize = 1 << 5, - HasFocus = 1 << 6, - Shaded = 1 << 7, - Stuck = 1 << 8, - Maximized = 1 << 9, - AllowsShade = 1 << 10, - AllowsMove = 1 << 11, - Fullscreen = 1 << 12, - IsFlashing = 1 << 13, - } -#endregion -} diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/FrameType.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/FrameType.cs deleted file mode 100644 index 7ecc08d277..0000000000 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/FrameType.cs +++ /dev/null @@ -1,22 +0,0 @@ -// This file was generated by the Gtk# code generator. -// Any changes made will be lost if regenerated. - -namespace Stetic.Metacity -{ - - using System; - using System.Runtime.InteropServices; - -#region Autogenerated code - internal enum FrameType { - - Normal, - Dialog, - ModalDialog, - Utility, - Menu, - Border, - Last, - } -#endregion -} diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ObjectManager.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ObjectManager.cs deleted file mode 100644 index 201c52370e..0000000000 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/ObjectManager.cs +++ /dev/null @@ -1,19 +0,0 @@ -// This file was generated by the Gtk# code generator. -// Any changes made will be lost if regenerated. - -namespace GtkSharp.MetacitySharp { - - class ObjectManager { - - static bool initialized = false; - // Call this method from the appropriate module init function. - public static void Initialize () - { - if (initialized) - return; - - initialized = true; - GLib.GType.Register (Stetic.Metacity.Preview.GType, typeof (Stetic.Metacity.Preview)); - } - } -} diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/Preview.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/Preview.cs deleted file mode 100644 index b0bd5ba026..0000000000 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/Preview.cs +++ /dev/null @@ -1,226 +0,0 @@ -// This file was generated by the Gtk# code generator. -// Any changes made will be lost if regenerated. - -namespace Stetic.Metacity { - - using System; - using System.Reflection; - using System.Collections; - using System.Runtime.InteropServices; - - internal class Preview : Gtk.Bin - { - const string LIBMETACITY = "libmetacity-private.so.0"; - static Theme theme; - public static bool ThemeError = false; - - public static Metacity.Preview Create (TopLevelWindow window) - { - Metacity.Preview metacityPreview; - - try { - Metacity.Preview.Init (); - metacityPreview = new Metacity.Preview (); - } - catch { - return null; - } - - switch (window.TypeHint) { - case Gdk.WindowTypeHint.Normal: - metacityPreview.FrameType = Metacity.FrameType.Normal; - break; - case Gdk.WindowTypeHint.Dialog: - metacityPreview.FrameType = window.Modal ? Metacity.FrameType.ModalDialog : Metacity.FrameType.Dialog; - break; - case Gdk.WindowTypeHint.Menu: - metacityPreview.FrameType = Metacity.FrameType.Menu; - break; - case Gdk.WindowTypeHint.Splashscreen: - metacityPreview.FrameType = Metacity.FrameType.Border; - break; - case Gdk.WindowTypeHint.Utility: - metacityPreview.FrameType = Metacity.FrameType.Utility; - break; - default: - metacityPreview.FrameType = Metacity.FrameType.Normal; - break; - } - - Metacity.FrameFlags flags = - Metacity.FrameFlags.AllowsDelete | - Metacity.FrameFlags.AllowsVerticalResize | - Metacity.FrameFlags.AllowsHorizontalResize | - Metacity.FrameFlags.AllowsMove | - Metacity.FrameFlags.AllowsShade | - Metacity.FrameFlags.HasFocus; - - if (window.Resizable) - flags = flags | Metacity.FrameFlags.AllowsMaximize; - - metacityPreview.FrameFlags = flags; - metacityPreview.ShowAll (); - metacityPreview.AddWindow (window); - - metacityPreview.Theme = GetTheme (); - - return metacityPreview; - } - - public void AddWindow (TopLevelWindow window) - { - base.Add (window); - - Title = window.Title ?? string.Empty; - window.PropertyChanged += OnWindowPropChange; - Destroyed += delegate { - window.PropertyChanged -= OnWindowPropChange; - }; - } - - void OnWindowPropChange (object ob, EventArgs e) - { - Title = ((TopLevelWindow)ob).Title ?? string.Empty; - } - - static Theme GetTheme () - { - if (theme == null) { - try { - Assembly assm = Assembly.LoadWithPartialName ("gconf-sharp"); - Type client_type = assm.GetType ("GConf.Client"); - MethodInfo method = client_type.GetMethod ("Get", BindingFlags.Instance | BindingFlags.Public); - object client = Activator.CreateInstance (client_type, new object[] { - - }); - string themeName = (string)method.Invoke (client, new object[] { "/apps/metacity/general/theme" }); - theme = Metacity.Theme.Load (themeName); - } catch { - // Set theme error flag - in case of a theme error a solid background needs to be drawn. - ThemeError = true; - // Don't crash if metacity is not available - return null; - } - } - return theme; - } - - /* static void GConfNotify (object obj, GConf.NotifyEventArgs args) - { - if (args.Key == "/apps/metacity/general/theme") { - theme = Metacity.Theme.Load ((string)args.Value); - foreach (Metacity.Preview prev in wrappers.Values) - prev.Theme = Theme; - } - } - */ - - ~Preview ( ) - { - Dispose(); - } - - public Preview(IntPtr raw) : base(raw) {} - - [DllImport(LIBMETACITY)] - static extern IntPtr meta_preview_new(); - - public Preview () : base (IntPtr.Zero) - { - if (GetType () != typeof (Preview)) { - CreateNativeObject (new string [0], new GLib.Value[0]); - return; - } - Raw = meta_preview_new(); - } - - [DllImport(LIBMETACITY)] - static extern void meta_preview_set_title(IntPtr raw, IntPtr title); - - public string Title { - set { - IntPtr title_as_native = GLib.Marshaller.StringToPtrGStrdup (value); - meta_preview_set_title(Handle, title_as_native); - GLib.Marshaller.Free (title_as_native); - } - } - - [DllImport(LIBMETACITY)] - static extern void meta_preview_set_button_layout(IntPtr raw, ref Stetic.Metacity.ButtonLayout button_layout); - - public Stetic.Metacity.ButtonLayout ButtonLayout - { - set { - meta_preview_set_button_layout(Handle, ref value); - } - } - - [DllImport(LIBMETACITY)] - static extern void meta_preview_set_theme(IntPtr raw, IntPtr theme); - - public Metacity.Theme Theme { - set { - meta_preview_set_theme(Handle, (value == null ? IntPtr.Zero : value.Handle)); - } - } - - [DllImport(LIBMETACITY)] - static extern IntPtr meta_preview_get_mini_icon(); - - public static Gdk.Pixbuf MiniIcon { - get { - IntPtr raw_ret = meta_preview_get_mini_icon(); - Gdk.Pixbuf ret = GLib.Object.GetObject(raw_ret) as Gdk.Pixbuf; - return ret; - } - } - - [DllImport(LIBMETACITY)] - static extern IntPtr meta_preview_get_icon(); - - public static Gdk.Pixbuf Icon { - get { - IntPtr raw_ret = meta_preview_get_icon(); - Gdk.Pixbuf ret = GLib.Object.GetObject(raw_ret) as Gdk.Pixbuf; - return ret; - } - } - - [DllImport(LIBMETACITY)] - static extern void meta_preview_set_frame_type(IntPtr raw, int type); - - public Stetic.Metacity.FrameType FrameType - { - set { - meta_preview_set_frame_type(Handle, (int) value); - } - } - - [DllImport(LIBMETACITY)] - static extern IntPtr meta_preview_get_type(); - - public static new GLib.GType GType { - get { - IntPtr raw_ret = meta_preview_get_type(); - GLib.GType ret = new GLib.GType(raw_ret); - return ret; - } - } - - [DllImport(LIBMETACITY)] - static extern void meta_preview_set_frame_flags(IntPtr raw, int flags); - - public Stetic.Metacity.FrameFlags FrameFlags - { - set { - meta_preview_set_frame_flags(Handle, (int) value); - } - } - - - public static void Init() - { - GtkSharp.MetacitySharp.ObjectManager.Initialize (); - } - } -} diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/Theme.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/Theme.cs deleted file mode 100644 index b9254d710d..0000000000 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/Metacity/Theme.cs +++ /dev/null @@ -1,41 +0,0 @@ - -namespace Stetic.Metacity -{ - using System; - using System.Runtime.InteropServices; - - internal class Theme : GLib.Opaque { - - public Theme (IntPtr raw) : base (raw) {} - - [DllImport("libmetacity-private.so.0")] - static extern IntPtr meta_theme_get_current (); - - public static Theme Current { - get { - IntPtr raw = meta_theme_get_current (); - return (Theme)GetOpaque (raw, typeof (Metacity.Theme), true); - } - } - - [DllImport("libmetacity-private.so.0")] - static extern IntPtr meta_theme_load (string theme_name, IntPtr err); - - public static Theme Load (string name) - { - IntPtr raw = meta_theme_load (name, IntPtr.Zero); - if (raw == IntPtr.Zero) - return null; - else - return (Theme)GetOpaque (raw, typeof (Metacity.Theme), true); - } - - [DllImport("libmetacity-private.so.0")] - static extern void meta_theme_free (IntPtr raw); - - protected override void Free (IntPtr raw) - { - meta_theme_free (Raw); - } - } -} diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/WidgetDesignerBackend.cs b/main/src/addins/MonoDevelop.GtkCore/libsteticui/WidgetDesignerBackend.cs index aad811474c..e3d6864c2c 100644 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/WidgetDesignerBackend.cs +++ b/main/src/addins/MonoDevelop.GtkCore/libsteticui/WidgetDesignerBackend.cs @@ -78,9 +78,7 @@ namespace Stetic TopLevelWindow window = container as TopLevelWindow; if (window != null) { - preview = Stetic.Metacity.Preview.Create (window); - if (preview == null) - preview = Stetic.Windows.Preview.Create (window); + preview = Stetic.Windows.Preview.Create (window); if (preview == null) { // Use a regular box. EventBox eventBox = new EventBox (); @@ -660,8 +658,7 @@ namespace Stetic PropagateExpose (cw, ev);*/ Gdk.Rectangle rect = child.Allocation; - if (Stetic.Metacity.Preview.ThemeError) - GdkWindow.DrawRectangle (this.Style.BackgroundGC (StateType.Normal), true, rect.X, rect.Y, rect.Width, rect.Height); + GdkWindow.DrawRectangle (this.Style.BackgroundGC (StateType.Normal), true, rect.X, rect.Y, rect.Width, rect.Height); Pixbuf sh = Shadow.AddShadow (rect.Width, rect.Height); GdkWindow.DrawPixbuf (this.Style.BackgroundGC (StateType.Normal), sh, 0, 0, rect.X - 5, rect.Y - 5, sh.Width, sh.Height, RgbDither.None, 0, 0); diff --git a/main/src/addins/MonoDevelop.GtkCore/libsteticui/libsteticui.csproj b/main/src/addins/MonoDevelop.GtkCore/libsteticui/libsteticui.csproj index fc38b4c1e5..fb9b52a59d 100644 --- a/main/src/addins/MonoDevelop.GtkCore/libsteticui/libsteticui.csproj +++ b/main/src/addins/MonoDevelop.GtkCore/libsteticui/libsteticui.csproj @@ -109,13 +109,6 @@ <Compile Include="GuiDispatchServerSink.cs" /> <Compile Include="GuiDispatchServerSinkProvider.cs" /> <Compile Include="LibraryCache.cs" /> - <Compile Include="Metacity\ButtonFunction.cs" /> - <Compile Include="Metacity\ButtonLayout.cs" /> - <Compile Include="Metacity\FrameFlags.cs" /> - <Compile Include="Metacity\FrameType.cs" /> - <Compile Include="Metacity\ObjectManager.cs" /> - <Compile Include="Metacity\Preview.cs" /> - <Compile Include="Metacity\Theme.cs" /> <Compile Include="Palette.cs" /> <Compile Include="PaletteBackend.cs" /> <Compile Include="PluggableWidget.cs" /> diff --git a/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs b/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs index 4a376c3fea..da22d92f36 100644 --- a/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs +++ b/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs @@ -71,7 +71,7 @@ namespace Mono.MHex.Rendering for (int i = 0; i < lineBytes.Length; i++) { byte b = lineBytes[i]; char ch = (char)b; - if (b < 128 && (Char.IsLetterOrDigit (ch) || Char.IsPunctuation (ch))) { + if (!char.IsControl (ch)) { sb.Append (ch); } else { sb.Append ("."); diff --git a/main/src/addins/MonoDevelop.HexEditor/MonoDevelop.HexEditor/HexEditorVisualizer.cs b/main/src/addins/MonoDevelop.HexEditor/MonoDevelop.HexEditor/HexEditorVisualizer.cs index 002444879c..9ea23c4739 100644 --- a/main/src/addins/MonoDevelop.HexEditor/MonoDevelop.HexEditor/HexEditorVisualizer.cs +++ b/main/src/addins/MonoDevelop.HexEditor/MonoDevelop.HexEditor/HexEditorVisualizer.cs @@ -81,12 +81,16 @@ namespace MonoDevelop.HexEditor public override Widget GetVisualizerWidget (ObjectValue val) { - hexEditor = new Mono.MHex.HexEditor (); + var options = DebuggingService.DebuggerSession.EvaluationOptions.Clone (); + options.AllowTargetInvoke = true; + options.ChunkRawStrings = true; IBuffer buffer = null; + hexEditor = new Mono.MHex.HexEditor (); + if (val.TypeName != "string") { - var raw = (RawValueArray) val.GetRawValue (); + var raw = (RawValueArray) val.GetRawValue (options); switch (val.TypeName) { case "sbyte[]": @@ -100,10 +104,7 @@ namespace MonoDevelop.HexEditor break; } } else { - var ops = DebuggingService.DebuggerSession.EvaluationOptions.Clone (); - ops.ChunkRawStrings = true; - - buffer = new RawStringBuffer ((RawValueString) val.GetRawValue (ops)); + buffer = new RawStringBuffer ((RawValueString) val.GetRawValue (options)); } hexEditor.HexEditorData.Buffer = buffer; @@ -119,13 +120,17 @@ namespace MonoDevelop.HexEditor public override bool StoreValue (ObjectValue val) { + var options = DebuggingService.DebuggerSession.EvaluationOptions.Clone (); + options.AllowTargetInvoke = true; + switch (val.TypeName) { case "byte[]": // HACK: make sure to load the full byte stream... long length = hexEditor.HexEditorData.Length; + hexEditor.HexEditorData.GetBytes (length - 1, 1); - val.SetRawValue (hexEditor.HexEditorData.Bytes); + val.SetRawValue (hexEditor.HexEditorData.Bytes, options); return true; default: return false; diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Commands/RestorePackagesInProjectHandler.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Commands/RestorePackagesInProjectHandler.cs new file mode 100644 index 0000000000..cd12b8ef75 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Commands/RestorePackagesInProjectHandler.cs @@ -0,0 +1,63 @@ +//
+// RestorePackagesInProjectHandler.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using MonoDevelop.Components.Commands;
+using MonoDevelop.Ide;
+using MonoDevelop.Projects;
+
+namespace MonoDevelop.PackageManagement.Commands
+{
+ public class RestorePackagesInProjectHandler : PackagesCommandHandler
+ {
+ protected override void Run ()
+ {
+ IDotNetProject project = GetSelectedProject ();
+ if (project == null)
+ return;
+
+ ProgressMonitorStatusMessage progressMessage = ProgressMonitorStatusMessageFactory.CreateRestoringPackagesInProjectMessage ();
+ var runner = new PackageRestoreRunner ();
+ DispatchService.BackgroundDispatch (() => {
+ runner.Run (project, progressMessage);
+ });
+ }
+
+ IDotNetProject GetSelectedProject ()
+ {
+ DotNetProject project = GetSelectedDotNetProject ();
+ if (project != null) {
+ return new DotNetProjectProxy (project);
+ }
+ return null;
+ }
+
+ protected override void Update (CommandInfo info)
+ {
+ info.Enabled = SelectedDotNetProjectOrSolutionHasPackages ();
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Gui/AddPackagesDialog.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Gui/AddPackagesDialog.cs index 642b59906e..ec8e0f7f69 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Gui/AddPackagesDialog.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Gui/AddPackagesDialog.cs @@ -289,7 +289,7 @@ namespace MonoDevelop.PackageManagement this.packageVersionLabel.Text = packageViewModel.Version.ToString ();
this.packageAuthor.Text = packageViewModel.GetAuthors ();
this.packagePublishedDate.Text = packageViewModel.GetLastPublishedDisplayText ();
- this.packageDownloads.Text = packageViewModel.GetDownloadCountOrVersionDisplayText ();
+ this.packageDownloads.Text = packageViewModel.GetDownloadCountDisplayText ();
this.packageDescription.Text = packageViewModel.Description;
this.packageId.Text = packageViewModel.Id;
this.packageId.Visible = packageViewModel.HasNoGalleryUrl;
@@ -532,6 +532,7 @@ namespace MonoDevelop.PackageManagement void PackageSearchEntryChanged (object sender, EventArgs e)
{
+ ClearErrorMessage ();
ClearPackages ();
UpdateAddPackagesButton ();
SearchAfterDelay ();
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNode.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNode.cs index 84928ce419..915328acfd 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNode.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNode.cs @@ -27,8 +27,8 @@ using System;
using System.Runtime.Versioning;
using MonoDevelop.Core;
-using MonoDevelop.Core.Serialization;
using MonoDevelop.Ide.Gui;
+using MonoDevelop.Ide.Tasks;
using NuGet;
namespace MonoDevelop.PackageManagement.NodeBuilders
@@ -91,15 +91,10 @@ namespace MonoDevelop.PackageManagement.NodeBuilders public string GetLabel ()
{
if (UpdatedVersion != null) {
- return GetIdText () + GetUpdatedVersionLabelText ();
+ return Id + GetUpdatedVersionLabelText ();
}
- return GetIdText ();
- }
-
- string GetIdText ()
- {
- if (!Installed || IsReinstallNeeded) {
- return "<span color='#c99c00'>" + Id + "</span>";
+ if (IsInstallPending) {
+ return Id + GetInstallingLabelText ();
}
return Id;
}
@@ -111,19 +106,47 @@ namespace MonoDevelop.PackageManagement.NodeBuilders GettextCatalog.GetString ("available"));
}
+ string GetInstallingLabelText ()
+ {
+ return String.Format (" ({0})", GettextCatalog.GetString ("installing"));
+ }
+
public IconId GetIconId ()
{
+ return Stock.Reference;
+ }
+
+ public string GetPackageVersionLabel ()
+ {
+ return GettextCatalog.GetString ("Version {0}", Version);
+ }
+
+ public TaskSeverity? GetStatusSeverity ()
+ {
if (!Installed || IsReinstallNeeded) {
if (!IsInstallPending) {
- return Stock.ReferenceWarning;
+ return TaskSeverity.Warning;
}
}
- return Stock.Reference;
+
+ return null;
}
- public string GetPackageVersionLabel ()
+ public string GetStatusMessage ()
{
- return GettextCatalog.GetString ("Version {0}", Version);
+ if (IsInstallPending) {
+ return null;
+ } else if (!Installed) {
+ return GettextCatalog.GetString ("Package is not restored");
+ } else if (IsReinstallNeeded) {
+ return GettextCatalog.GetString ("Package needs retargeting");
+ }
+ return null;
+ }
+
+ public bool IsDisabled ()
+ {
+ return (!Installed || IsInstallPending);
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNodeBuilder.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNodeBuilder.cs index 0af1f56798..149b61f265 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/PackageReferenceNodeBuilder.cs @@ -58,6 +58,9 @@ namespace MonoDevelop.PackageManagement.NodeBuilders var packageReferenceNode = (PackageReferenceNode)dataObject;
nodeInfo.Label = packageReferenceNode.GetLabel ();
nodeInfo.Icon = Context.GetIcon (packageReferenceNode.GetIconId ());
+ nodeInfo.StatusSeverity = packageReferenceNode.GetStatusSeverity ();
+ nodeInfo.StatusMessage = packageReferenceNode.GetStatusMessage ();
+ nodeInfo.DisabledStyle = packageReferenceNode.IsDisabled ();
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesFolderNodeBuilder.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesFolderNodeBuilder.cs index 631b33e9b2..0fd8f7242f 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesFolderNodeBuilder.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesFolderNodeBuilder.cs @@ -81,7 +81,7 @@ namespace MonoDevelop.PackageManagement.NodeBuilders List<PackageReferenceNode> nodes = projectPackagesNode.GetPackageReferencesNodes ().ToList ();
foreach (InstallPackageAction installAction in GetPendingInstallActions (projectPackagesNode.Project)) {
- if (!nodes.Any (node => node.Id == installAction.Package.Id)) {
+ if (!nodes.Any (node => node.Id == installAction.GetPackageId ())) {
nodes.Add (CreatePackageReferenceNode (installAction));
}
}
@@ -99,7 +99,7 @@ namespace MonoDevelop.PackageManagement.NodeBuilders PackageReferenceNode CreatePackageReferenceNode (InstallPackageAction installAction)
{
return new PackageReferenceNode (
- new PackageReference (installAction.Package.Id, installAction.Package.Version, null, null, false),
+ new PackageReference (installAction.GetPackageId (), installAction.GetPackageVersion (), null, null, false),
false,
true);
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesProjectNodeBuilderExtension.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesProjectNodeBuilderExtension.cs index 3bdec1ec1c..b30f68b1c5 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesProjectNodeBuilderExtension.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.NodeBuilders/ProjectPackagesProjectNodeBuilderExtension.cs @@ -144,16 +144,7 @@ namespace MonoDevelop.PackageManagement.NodeBuilders bool IsPackagesConfigFileChanged (FileEventArgs fileEventArgs)
{
- return fileEventArgs.Any (file => IsPackagesConfigFileName (file.FileName));
- }
-
- bool IsPackagesConfigFileName (FilePath filePath)
- {
- if (filePath == null) {
- return false;
- }
-
- return Constants.PackageReferenceFile.Equals (filePath.FileName, StringComparison.OrdinalIgnoreCase);
+ return fileEventArgs.Any (file => file.FileName.IsPackagesConfigFileName ());
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/ExceptionThrowingPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/ExceptionThrowingPackageRepository.cs new file mode 100644 index 0000000000..b5308eaa74 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/ExceptionThrowingPackageRepository.cs @@ -0,0 +1,53 @@ +//
+// ExceptionThrowingPackageRepository.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement.Tests.Helpers
+{
+ public class ExceptionThrowingPackageRepository : FakePackageRepository
+ {
+ public Exception GetPackagesException;
+
+ public ExceptionThrowingPackageRepository ()
+ : this (new Exception ("Error"))
+ {
+ }
+
+ public ExceptionThrowingPackageRepository (Exception exception)
+ {
+ GetPackagesException = exception;
+ }
+
+ public override IQueryable<IPackage> GetPackages ()
+ {
+ throw GetPackagesException;
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeFileRemover.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeFileRemover.cs new file mode 100644 index 0000000000..7f80fec744 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeFileRemover.cs @@ -0,0 +1,41 @@ +//
+// FakeFileRemover.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace MonoDevelop.PackageManagement.Tests.Helpers
+{
+ public class FakeFileRemover : IFileRemover
+ {
+ public string FileRemoved;
+
+ public void RemoveFile (string fileName)
+ {
+ FileRemoved = fileName;
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeOperationAwareRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeOperationAwareRepository.cs index 7bbdce5119..e3e769d494 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeOperationAwareRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeOperationAwareRepository.cs @@ -34,11 +34,13 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers {
public string OperationStarted;
public string MainPackageIdForOperationStarted;
+ public string MainPackageVersionForOperationStarted;
public IDisposable StartOperation (string operationName, string mainPackageId, string mainPackageVersion)
{
OperationStarted = operationName;
MainPackageIdForOperationStarted = mainPackageId;
+ MainPackageVersionForOperationStarted = mainPackageVersion;
return this;
}
@@ -49,6 +51,14 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers AssertOperationIsDisposed ();
}
+ public void AssertOperationWasStartedAndDisposed (string expectedOperationName, string expectedMainPackageId, string expectedMainPackageVersion)
+ {
+ Assert.AreEqual (expectedOperationName, OperationStarted);
+ Assert.AreEqual (expectedMainPackageId, MainPackageIdForOperationStarted);
+ Assert.AreEqual (expectedMainPackageVersion, MainPackageVersionForOperationStarted);
+ AssertOperationIsDisposed ();
+ }
+
void AssertOperationIsDisposed ()
{
Assert.IsTrue (IsDisposed);
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackage.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackage.cs index 4601469c9b..1a22b06d86 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackage.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackage.cs @@ -63,6 +63,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers this.Version = new SemanticVersion (version);
this.Listed = true;
this.IsLatestVersion = true;
+ IsValid = true;
}
public static FakePackage CreatePackageWithVersion (string version)
@@ -228,6 +229,8 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public Uri GalleryUrl { get; set; }
public bool DevelopmentDependency { get; set; }
+
+ public bool IsValid { get; set; }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementProject.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementProject.cs index 6eb845018a..9e3e9e141b 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementProject.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementProject.cs @@ -51,7 +51,17 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers return FakePackages.FirstOrDefault (package => package.Id == packageId);
};
+ UpdatePackageAction = (package, updateAction) => {
+ PackagePassedToUpdatePackage = package;
+ PackageOperationsPassedToUpdatePackage = updateAction.Operations;
+ UpdateDependenciesPassedToUpdatePackage = updateAction.UpdateDependencies;
+ AllowPrereleaseVersionsPassedToUpdatePackage = updateAction.AllowPrereleaseVersions;
+ IsUpdatePackageCalled = true;
+ };
+
this.Name = name;
+
+ ConstraintProvider = NullConstraintProvider.Instance;
}
public FakeUninstallPackageAction FakeUninstallPackageAction;
@@ -156,13 +166,11 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public void UpdatePackage (IPackage package, UpdatePackageAction updateAction)
{
- PackagePassedToUpdatePackage = package;
- PackageOperationsPassedToUpdatePackage = updateAction.Operations;
- UpdateDependenciesPassedToUpdatePackage = updateAction.UpdateDependencies;
- AllowPrereleaseVersionsPassedToUpdatePackage = updateAction.AllowPrereleaseVersions;
- IsUpdatePackageCalled = true;
+ UpdatePackageAction (package, updateAction);
}
+ public Action<IPackage, UpdatePackageAction> UpdatePackageAction;
+
public FakeInstallPackageAction LastInstallPackageCreated;
public virtual InstallPackageAction CreateInstallPackageAction ()
@@ -248,6 +256,11 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers FakeSourceRepository.AddFakePackage (packageId);
}
+ public FakePackage AddFakePackageToSourceRepository (string packageId, string version)
+ {
+ return FakeSourceRepository.AddFakePackageWithVersion (packageId, version);
+ }
+
public void UpdatePackages (UpdatePackagesAction action)
{
}
@@ -364,6 +377,8 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers {
throw new NotImplementedException ();
}
+
+ public IPackageConstraintProvider ConstraintProvider { get; set; }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementSolution.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementSolution.cs index 7185d1c5d4..adfddb3d8e 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementSolution.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagementSolution.cs @@ -198,6 +198,26 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers {
throw new NotImplementedException ();
}
+
+ public FakeSolutionPackageRepository SolutionPackageRepository = new FakeSolutionPackageRepository ();
+
+ public ISolutionPackageRepository GetRepository ()
+ {
+ return SolutionPackageRepository;
+ }
+
+ public bool IsPackageRestored (string packageId, SemanticVersion packageVersion)
+ {
+ return FakeInstalledPackages.Any (package => {
+ return (package.Id == packageId) &&
+ (package.Version == packageVersion);
+ });
+ }
+
+ public void AddPackageReference (string packageId, string packageVersion)
+ {
+ SolutionPackageRepository.AddPackageReference (packageId, packageVersion);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManager.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManager.cs index a9a722a48a..a6a3c7787c 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManager.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManager.cs @@ -214,11 +214,23 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers SettingsPassedToUpdatePackageReference = settings;
}
+ public bool IgnoreWalkInfoPassedToInstallPackage;
+ public bool IsPackageInstalled;
+
public void InstallPackage (IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions, bool ignoreWalkInfo)
{
- throw new NotImplementedException ();
+ IsPackageInstalled = true;
+
+ PackagePassedToInstallPackage = package;
+ IgnoreDependenciesPassedToInstallPackage = ignoreDependencies;
+ AllowPrereleaseVersionsPassedToInstallPackage = allowPrereleaseVersions;
+ IgnoreWalkInfoPassedToInstallPackage = ignoreWalkInfo;
+
+ PackagesInstalled.Add (package);
}
+ public List<IPackage> PackagesInstalled = new List<IPackage> ();
+
public DependencyVersion DependencyVersion {
get {
throw new NotImplementedException ();
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagerFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagerFactory.cs index bb98bc2097..e66d160c69 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagerFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageManagerFactory.cs @@ -36,6 +36,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public FakePackageManager FakePackageManager = new FakePackageManager ();
public IPackageRepository PackageRepositoryPassedToCreatePackageManager;
public IDotNetProject ProjectPassedToCreateRepository;
+ public ISolutionPackageRepository SolutionPackageRepositoryPassedToCreatePackageManager;
public ISharpDevelopPackageManager CreatePackageManager (IPackageRepository sourceRepository, IDotNetProject project)
{
@@ -43,6 +44,13 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers ProjectPassedToCreateRepository = project;
return FakePackageManager;
}
+
+ public IPackageManager CreatePackageManager (IPackageRepository sourceRepository, ISolutionPackageRepository solutionPackageRepository)
+ {
+ PackageRepositoryPassedToCreatePackageManager = sourceRepository;
+ SolutionPackageRepositoryPassedToCreatePackageManager = solutionPackageRepository;
+ return FakePackageManager;
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepository.cs index 2e7bffe160..93dea0d78d 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepository.cs @@ -42,7 +42,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers get { return PackagesAdded [0]; }
}
- public IQueryable<IPackage> GetPackages ()
+ public virtual IQueryable<IPackage> GetPackages ()
{
return FakePackages.AsQueryable ();
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepositoryFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepositoryFactory.cs index c55a3679a4..cf406c1fd5 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepositoryFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepositoryFactory.cs @@ -117,6 +117,13 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public IRecentPackageRepository RecentPackageRepository {
get { return FakeRecentPackageRepository; }
}
+
+ public FakePackageRepository FakePriorityPackageRepository = new FakePackageRepository ();
+
+ public IPackageRepository CreateAggregateWithPriorityMachineCacheRepository ()
+ {
+ return FakePriorityPackageRepository;
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepositoryWithConstraintProvider.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepositoryWithConstraintProvider.cs new file mode 100644 index 0000000000..a39b13097a --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakePackageRepositoryWithConstraintProvider.cs @@ -0,0 +1,47 @@ +//
+// FakePackageRepositoryWithConstraintProvider.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement.Tests.Helpers
+{
+ public class FakePackageRepositoryWithConstraintProvider : FakePackageRepository, IPackageConstraintProvider
+ {
+ DefaultConstraintProvider constraintProvider = new DefaultConstraintProvider ();
+
+ public IVersionSpec GetConstraint (string packageId)
+ {
+ return constraintProvider.GetConstraint (packageId);
+ }
+
+ public void AddConstraint (string packageId, IVersionSpec versionSpec)
+ {
+ constraintProvider.AddConstraint (packageId, versionSpec);
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitor.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitor.cs index a06a2dc3df..3f00df6491 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitor.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitor.cs @@ -29,14 +29,15 @@ using System.IO; using System.Text;
using MonoDevelop.Core;
using NUnit.Framework;
+using System.Threading;
namespace MonoDevelop.PackageManagement.Tests.Helpers
{
- public class FakeProgressMonitor : IProgressMonitor
+ public class FakeProgressMonitor : ProgressMonitor
{
public event MonitorHandler CancelRequested;
- protected virtual void OnCancelRequested (IProgressMonitor monitor)
+ protected virtual void OnCancelRequested (ProgressMonitor monitor)
{
var handler = CancelRequested;
if (handler != null)
@@ -48,7 +49,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers Log = new StringWriter (LoggedMessages);
}
- public void BeginTask (string name, int totalWork)
+ protected override void OnBeginTask (string name, int totalWork, int stepWork)
{
BeginTaskTotalWork = totalWork;
}
@@ -59,14 +60,14 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers {
}
- public void EndTask ()
+ protected override void OnEndTask (string name, int totalWork, int stepWork)
{
IsTaskEnded = true;
}
public bool IsTaskEnded;
- public void Step (int work)
+ protected override void OnStep (string message, int work)
{
StepCalledCount++;
TotalStepWork += work;
@@ -75,21 +76,21 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public int StepCalledCount;
public int TotalStepWork;
- public void ReportWarning (string message)
+ protected override void OnWarningReported (string message)
{
ReportedWarningMessage = message;
}
public string ReportedWarningMessage;
- public void ReportSuccess (string message)
+ protected override void OnSuccessReported (string message)
{
ReportedSuccessMessage = message;
}
public string ReportedSuccessMessage;
- public void ReportError (string message, Exception exception)
+ protected override void OnErrorReported (string message, Exception exception)
{
ReportedErrorMessage = message;
}
@@ -110,13 +111,13 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers Assert.IsFalse (log.Contains (message), log);
}
- public TextWriter Log { get; set; }
public bool IsCancelRequested { get; set; }
- public IAsyncOperation AsyncOperation { get; set; }
+ public AsyncOperation AsyncOperation { get; set; }
public object SyncRoot { get; set; }
- public void Dispose ()
+ public override void Dispose ()
{
+ base.Dispose ();
IsDisposed = true;
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitorFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitorFactory.cs index 90e62b3268..f7b28eb358 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitorFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProgressMonitorFactory.cs @@ -34,7 +34,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public FakeProgressMonitor ProgressMonitor = new FakeProgressMonitor ();
public string StatusText;
- public IProgressMonitor CreateProgressMonitor (string statusText)
+ public ProgressMonitor CreateProgressMonitor (string statusText)
{
StatusText = statusText;
return ProgressMonitor;
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProject.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProject.cs index 18971e4641..cdab5a07b6 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProject.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeProject.cs @@ -27,6 +27,7 @@ using System;
using System.Collections;
using MonoDevelop.Core;
+using System.Collections.Generic;
namespace MonoDevelop.PackageManagement.Tests.Helpers
{
@@ -61,6 +62,10 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers {
IsSaved = true;
}
+
+ public IEnumerable<string> FlavorGuids {
+ get { yield break; }
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeSolutionPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeSolutionPackageRepository.cs index 26be2ad35d..eaf9dcf505 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeSolutionPackageRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/FakeSolutionPackageRepository.cs @@ -81,6 +81,33 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public IFileSystem FileSystem { get; set; }
public IPackagePathResolver PackagePathResolver { get; set; }
+
+ public bool IsRestored (PackageReference packageReference)
+ {
+ return FakeSharedRepository.FakePackages.Any (package => {
+ return (package.Id == packageReference.Id) &&
+ (package.Version == packageReference.Version);
+ });
+ }
+
+ public List<PackageReference> PackageReferences = new List<PackageReference> ();
+
+ public void AddPackageReference (string packageId, string packageVersion)
+ {
+ var packageReference = new PackageReference (
+ packageId,
+ new SemanticVersion (packageVersion),
+ null,
+ null,
+ false,
+ false);
+ PackageReferences.Add (packageReference);
+ }
+
+ public IEnumerable<PackageReference> GetPackageReferences ()
+ {
+ return PackageReferences;
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableBackgroundPackageActionRunner.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableBackgroundPackageActionRunner.cs index 66439b08e1..d4b11accde 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableBackgroundPackageActionRunner.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableBackgroundPackageActionRunner.cs @@ -60,7 +60,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers }
protected override PackageManagementEventsMonitor CreateEventMonitor (
- IProgressMonitor monitor,
+ ProgressMonitor monitor,
IPackageManagementEvents packageManagementEvents,
IProgressProvider progressProvider)
{
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableLocalPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableLocalPackageRepository.cs new file mode 100644 index 0000000000..81fe190099 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableLocalPackageRepository.cs @@ -0,0 +1,59 @@ +//
+// TestableLocalPackageRepository.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement.Tests.Helpers
+{
+ public class TestableLocalPackageRepository : LocalPackageRepository
+ {
+ public TestableLocalPackageRepository ()
+ : base (@"d:\projects\MySolution\packages".ToNativePath ())
+ {
+ }
+
+ public override IEnumerable<string> GetPackageLookupPaths (string packageId, SemanticVersion version)
+ {
+ var packageName = new PackageName (packageId, version);
+ List<string> filePaths = null;
+ if (packageLookupPaths.TryGetValue (packageName, out filePaths)) {
+ return filePaths;
+ }
+ return Enumerable.Empty<string> ();
+ }
+
+ Dictionary<PackageName, List<string>> packageLookupPaths = new Dictionary<PackageName, List<string>> ();
+
+ public void AddPackageLookupPath (PackageName packageName, params string[] filePaths)
+ {
+ packageLookupPaths.Add (packageName, filePaths.ToList ());
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageCompatibilityRunner.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageCompatibilityRunner.cs index 2ebee582a5..7045d5acf2 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageCompatibilityRunner.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageCompatibilityRunner.cs @@ -65,7 +65,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers }
protected override PackageManagementEventsMonitor CreateEventMonitor (
- IProgressMonitor monitor,
+ ProgressMonitor monitor,
IPackageManagementEvents packageManagementEvents,
IProgressProvider progressProvider)
{
@@ -97,7 +97,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public bool PackageConsoleIsShown;
- protected override void ShowPackageConsole (IProgressMonitor progressMonitor)
+ protected override void ShowPackageConsole (ProgressMonitor progressMonitor)
{
PackageConsoleIsShown = true;
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageManagementEventsMonitor.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageManagementEventsMonitor.cs index 451310dd19..995fa795cb 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageManagementEventsMonitor.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestablePackageManagementEventsMonitor.cs @@ -36,7 +36,7 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers public class TestablePackageManagementEventsMonitor : PackageManagementEventsMonitor
{
public TestablePackageManagementEventsMonitor (
- IProgressMonitor progressMonitor,
+ ProgressMonitor progressMonitor,
IPackageManagementEvents packageManagementEvents,
IProgressProvider progressProvider)
: base (progressMonitor, packageManagementEvents, progressProvider)
@@ -55,14 +55,14 @@ namespace MonoDevelop.PackageManagement.Tests.Helpers handler.Invoke ();
}
- protected override void ShowPackageConsole (IProgressMonitor progressMonitor)
+ protected override void ShowPackageConsole (ProgressMonitor progressMonitor)
{
IsPackageConsoleShown = true;
ProgressMonitorPassedToShowPackageConsole = progressMonitor;
}
public bool IsPackageConsoleShown;
- public IProgressMonitor ProgressMonitorPassedToShowPackageConsole;
+ public ProgressMonitor ProgressMonitorPassedToShowPackageConsole;
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableSolutionPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableSolutionPackageRepository.cs new file mode 100644 index 0000000000..78cbae75c9 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.Helpers/TestableSolutionPackageRepository.cs @@ -0,0 +1,51 @@ +//
+// TestableSolutionPackageRepository.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using ICSharpCode.PackageManagement;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement.Tests.Helpers
+{
+ public class TestableSolutionPackageRepository : SolutionPackageRepository
+ {
+ public TestableSolutionPackageRepository (
+ ISolution solution,
+ ISharpDevelopPackageRepositoryFactory repositoryFactory,
+ PackageManagementOptions options)
+ : base (solution, repositoryFactory, options)
+ {
+ }
+
+ public TestableLocalPackageRepository LocalPackageRepository = new TestableLocalPackageRepository ();
+
+ protected override LocalPackageRepository CreateLocalPackageRepository ()
+ {
+ return LocalPackageRepository;
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.csproj b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.csproj index 8545b6caed..f7d81fb679 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.csproj +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests.csproj @@ -122,7 +122,6 @@ <Compile Include="MonoDevelop.PackageManagement.Tests\UpdateAllPackagesInSolutionTests.cs" /> <Compile Include="MonoDevelop.PackageManagement.Tests\UserAgentGeneratorForRepositoryRequestsTests.cs" /> <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\FakePackageRepositoryWithHttpClientEvents.cs" /> - <Compile Include="MonoDevelop.PackageManagement.Tests\NuGetPackageRestoreCommandLineTests.cs" /> <Compile Include="MonoDevelop.PackageManagement.Tests\ReducedPackageOperationsTests.cs" /> <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\TestPackageHelper.cs" /> <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\FakePackageOperationResolver.cs" /> @@ -193,6 +192,13 @@ <Compile Include="MonoDevelop.PackageManagement.Tests\PackagesViewModelTests.cs" /> <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\TestablePackagesViewModel.cs" /> <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\PageCollectionAssert.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\ExceptionThrowingPackageRepository.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Tests\MonoDevelopAggregateRepositoryTests.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Tests\RestorePackagesActionTests.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\TestableLocalPackageRepository.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\TestableSolutionPackageRepository.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\FakeFileRemover.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Tests.Helpers\FakePackageRepositoryWithConstraintProvider.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\core\MonoDevelop.Core\MonoDevelop.Core.csproj"> diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/AvailablePackagesViewModelTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/AvailablePackagesViewModelTests.cs index 664e6fa424..75f49fdc55 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/AvailablePackagesViewModelTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/AvailablePackagesViewModelTests.cs @@ -60,6 +60,7 @@ namespace MonoDevelop.PackageManagement.Tests ExceptionThrowingRegisteredPackageRepositories exceptionThrowingRegisteredPackageRepositories;
FakeTaskFactory taskFactory;
FakeRecentPackageRepository recentPackageRepository;
+ FakePackageManagementSolution solution;
void CreateViewModel ()
{
@@ -77,8 +78,10 @@ namespace MonoDevelop.PackageManagement.Tests taskFactory = new FakeTaskFactory ();
var packageViewModelFactory = new FakePackageViewModelFactory ();
recentPackageRepository = new FakeRecentPackageRepository ();
+ solution = new FakePackageManagementSolution ();
viewModel = new AvailablePackagesViewModel (
+ solution,
registeredPackageRepositories,
recentPackageRepository,
packageViewModelFactory,
@@ -172,6 +175,39 @@ namespace MonoDevelop.PackageManagement.Tests viewModel.SearchTerms = string.Format ("{0} version:{1}", packageId, versions).TrimEnd ();
}
+ void AddAggregateRepositoryWithOneFailingRepository ()
+ {
+ AddAggregateRepository (new ExceptionThrowingPackageRepository (), new FakePackageRepository ());
+ }
+
+ void AddAggregateRepository (params IPackageRepository[] repositories)
+ {
+ var repository = new MonoDevelopAggregateRepository (repositories);
+ registeredPackageRepositories.ActivePackageSource = registeredPackageRepositories.PackageSources [0];
+ registeredPackageRepositories.GetActiveRepositoryAction = () => {
+ return repository;
+ };
+ }
+
+ void AddAggregateRepositoryWithJustFailingRepositories ()
+ {
+ AddAggregateRepository (new ExceptionThrowingPackageRepository (), new ExceptionThrowingPackageRepository ());
+ }
+
+ void AddAggregateRepositoryWithTwoFailingRepositories (Exception exception1, Exception exception2)
+ {
+ AddAggregateRepository (
+ new ExceptionThrowingPackageRepository (exception1),
+ new ExceptionThrowingPackageRepository (exception2));
+ }
+
+ FakePackage AddPackageToSolution (string packageId, string packageVersion)
+ {
+ var package = FakePackage.CreatePackageWithVersion (packageId, packageVersion);
+ solution.SolutionPackageRepository.FakePackages.Add (package);
+ return package;
+ }
+
[Test]
public void ReadPackages_RepositoryHasThreePackagesWithSameIdButDifferentVersions_HasLatestPackageVersionOnly ()
{
@@ -809,9 +845,6 @@ namespace MonoDevelop.PackageManagement.Tests viewModel.ReadPackages ();
CompleteReadPackagesTask ();
- var expectedPackages = new FakePackage[] {
- package2, package1
- };
Assert.IsTrue (viewModel.PackageViewModels [0].ShowVersionInsteadOfDownloadCount);
Assert.IsTrue (viewModel.PackageViewModels [1].ShowVersionInsteadOfDownloadCount);
}
@@ -831,9 +864,6 @@ namespace MonoDevelop.PackageManagement.Tests viewModel.ReadPackages ();
CompleteReadPackagesTask ();
- var expectedPackages = new FakePackage[] {
- package2, package1
- };
Assert.IsFalse (viewModel.PackageViewModels [0].ShowVersionInsteadOfDownloadCount);
Assert.IsFalse (viewModel.PackageViewModels [1].ShowVersionInsteadOfDownloadCount);
}
@@ -911,5 +941,276 @@ namespace MonoDevelop.PackageManagement.Tests };
PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
}
+
+ [Test]
+ public void ReadPackages_ActivePackageSourceIsAggregatePackageRepositoryWithOneFailingRepository_HasErrorIsTrueAndErrorMessageHasWarning ()
+ {
+ CreateRegisteredPackageRepositories ();
+ AddAggregateRepositoryWithOneFailingRepository ();
+ CreateViewModel (registeredPackageRepositories);
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ Assert.IsTrue (viewModel.HasError);
+ Assert.That (viewModel.ErrorMessage, Contains.Substring ("Some package sources could not be reached."));
+ }
+
+ [Test]
+ public void ReadPackages_ActivePackageSourceIsAggregatePackageRepositoryWithAllRepositoriesFailing_HasErrorIsTrueAndErrorMessageHasWarning ()
+ {
+ CreateRegisteredPackageRepositories ();
+ AddAggregateRepositoryWithJustFailingRepositories ();
+ CreateViewModel (registeredPackageRepositories);
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ Assert.IsTrue (viewModel.HasError);
+ Assert.That (viewModel.ErrorMessage, Contains.Substring ("All package sources could not be reached."));
+ }
+
+ [Test]
+ public void ReadPackages_ActivePackageSourceIsAggregatePackageRepositoryWithAllRepositoriesFailing_RepositoryErrorIsDisplayed ()
+ {
+ CreateRegisteredPackageRepositories ();
+ var exception1 = new Exception ("Error1");
+ var exception2 = new Exception ("Error2");
+ AddAggregateRepositoryWithTwoFailingRepositories (exception1, exception2);
+ CreateViewModel (registeredPackageRepositories);
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ Assert.IsTrue (viewModel.HasError);
+ Assert.That (viewModel.ErrorMessage, Contains.Substring ("Error1"));
+ Assert.That (viewModel.ErrorMessage, Contains.Substring ("Error2"));
+ }
+
+ [Test]
+ public void ReadPackages_ActivePackageSourceIsAggregatePackageRepositoryWithOneFailingRepository_RepositoryErrorIsDisplayed ()
+ {
+ CreateRegisteredPackageRepositories ();
+ var repository = new ExceptionThrowingPackageRepository (new Exception ("Error1"));
+ AddAggregateRepository (new FakePackageRepository (), repository);
+ CreateViewModel (registeredPackageRepositories);
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ Assert.IsTrue (viewModel.HasError);
+ Assert.That (viewModel.ErrorMessage, Contains.Substring ("Error1"));
+ }
+
+ [Test]
+ public void ReadPackages_OneRecentPackageIsAvailable_RecentPackageIsDisplayedBeforeAnyOtherPackages ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "0.2.0.0");
+ var package2 = new FakePackage ("Aa", "0.3.0.0");
+ var packages = new [] {
+ package1, package2
+ };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ var recentPackage = new FakePackage ("B", "1.0.0.0");
+ recentPackageRepository.AddPackage (recentPackage);
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ recentPackage, package1, package2
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_OneRecentPackageIsAvailableWhichMatchesPackageFromActiveSource_DuplicatePackageWithSameVersionFromActivePackageSourceIsNotDisplayed ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "1.0.0.0");
+ var package2 = new FakePackage ("B", "0.3.0.0");
+ var packages = new [] {
+ package1, package2
+ };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ var recentPackage = new FakePackage ("A", "1.0.0.0");
+ recentPackageRepository.AddPackage (recentPackage);
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ recentPackage, package2
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_TwoRecentPackageAndSearchTextEntered_RecentPackagesAreFilteredBySearch ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "1.0.0.0");
+ var package2 = new FakePackage ("B", "0.3.0.0");
+ var packages = new [] {
+ package1, package2
+ };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ var recentPackage = new FakePackage ("Aa", "1.0.0.0");
+ recentPackageRepository.AddPackage (recentPackage);
+ recentPackageRepository.AddPackage (new FakePackage ("Bb", "1.0.0.0"));
+ viewModel.SearchTerms = "a";
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ recentPackage, package1
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_SolutionHasOnePackageInstalled_SolutionPackageDisplayedBeforeActivePackageSourcePackages ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "1.0.0.0");
+ var package2 = new FakePackage ("B", "0.3.0.0");
+ var packages = new [] {
+ package1, package2
+ };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ FakePackage installedPackage = AddPackageToSolution ("ZZ", "1.0.0.0");
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ installedPackage, package1, package2
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_SolutionHasOnePackageInstalledAndSecondPageOfPackagesIsReadWhenInfiniteScrollIsEnabled_SolutionPackageIsNotAddedTwice ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "1.0.0.0");
+ var package2 = new FakePackage ("B", "0.3.0.0");
+ var package3 = new FakePackage ("C", "0.1.0.0");
+ var package4 = new FakePackage ("D", "0.1.0.0");
+ var packages = new [] {
+ package1, package2, package3, package4
+ };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ FakePackage installedPackage = AddPackageToSolution ("ZZ", "1.0.0.0");
+ viewModel.PageSize = 2;
+ viewModel.ClearPackagesOnPaging = false;
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+ viewModel.ShowNextPage ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ installedPackage, package1, package2, package3, package4
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_OneSolutionPackageMatchesPackageFromActiveSource_DuplicatePackageWithSameVersionFromActiveSourceIsNotDisplayed ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "1.0.0.0");
+ var package2 = new FakePackage ("B", "0.3.0.0");
+ var packages = new [] {
+ package1, package2
+ };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ FakePackage installedPackage = AddPackageToSolution ("A", "1.0.0.0");
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ installedPackage, package2
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_OneSolutionPackageMatchesRecentPackage_DuplicateSolutionPackageWithSameVersionIsNotDisplayed ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "1.0.0.0");
+ var package2 = new FakePackage ("B", "0.3.0.0");
+ var packages = new [] {
+ package1, package2
+ };
+ var recentPackage = new FakePackage ("A", "1.0.0.0");
+ recentPackageRepository.AddPackage (recentPackage);
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ FakePackage installedPackage = AddPackageToSolution ("A", "1.0.0.0");
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ recentPackage, package2
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_SearchForAllPackageVersionsWhenOneSolutionPackageAvailable_SolutionPackageIsNotDisplayed ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "0.1.0.0") { IsLatestVersion = false };
+ var package2 = new FakePackage ("A", "0.2.0.0");
+ FakePackage installedPackage = AddPackageToSolution ("A", "1.0.0.0");
+ var packages = new [] { package1, package2 };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ SearchForAllPackageVersions ("A");
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new FakePackage[] {
+ package2, package1
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
+
+ [Test]
+ public void ReadPackages_TwoSolutionPackagesAndSearchTextEntered_SolutionPackagesAreFilteredBySearch ()
+ {
+ CreateViewModel ();
+ AddOnePackageSourceToRegisteredSources ();
+ var package1 = new FakePackage ("A", "1.0.0.0");
+ var package2 = new FakePackage ("B", "0.3.0.0");
+ var packages = new [] {
+ package1, package2
+ };
+ registeredPackageRepositories.FakeActiveRepository.FakePackages.AddRange (packages);
+ FakePackage installedPackage = AddPackageToSolution ("Aa", "1.0.0.0");
+ AddPackageToSolution ("Bb", "1.0.0.0");
+ viewModel.SearchTerms = "a";
+
+ viewModel.ReadPackages ();
+ CompleteReadPackagesTask ();
+
+ var expectedPackages = new [] {
+ installedPackage, package1
+ };
+ PackageCollectionAssert.AreEqual (expectedPackages, viewModel.PackageViewModels);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/InstallPackageActionTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/InstallPackageActionTests.cs index da59bdb7c8..758341f3a6 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/InstallPackageActionTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/InstallPackageActionTests.cs @@ -438,7 +438,6 @@ namespace MonoDevelop.PackageManagement.Tests CreateAction ();
FakePackage expectedPackage = fakeProject.FakeSourceRepository.AddFakePackageWithVersion ("Test", "1.0");
expectedPackage.RequireLicenseAcceptance = true;
- var expectedPackages = new IPackage [] { expectedPackage };
var operation = new FakePackageOperation (expectedPackage, PackageAction.Install);
action.PackageId = expectedPackage.Id;
action.PackageVersion = expectedPackage.Version;
@@ -460,7 +459,6 @@ namespace MonoDevelop.PackageManagement.Tests CreateAction ();
FakePackage expectedPackage = fakeProject.FakeSourceRepository.AddFakePackageWithVersion ("Test", "1.0");
expectedPackage.RequireLicenseAcceptance = true;
- var expectedPackages = new IPackage [] { expectedPackage };
var operation = new FakePackageOperation (expectedPackage, PackageAction.Install);
action.PackageId = expectedPackage.Id;
action.PackageVersion = expectedPackage.Version;
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/MonoDevelopAggregateRepositoryTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/MonoDevelopAggregateRepositoryTests.cs new file mode 100644 index 0000000000..b972f4a812 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/MonoDevelopAggregateRepositoryTests.cs @@ -0,0 +1,194 @@ +//
+// AggregateRepositoryTests.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using NUnit.Framework;
+using NuGet;
+using System.Collections.Generic;
+using MonoDevelop.PackageManagement.Tests.Helpers;
+using System.Linq;
+
+namespace MonoDevelop.PackageManagement.Tests
+{
+ [TestFixture]
+ public class MonoDevelopAggregateRepositoryTests
+ {
+ MonoDevelopAggregateRepository aggregateRepository;
+ List<IPackageRepository> repositories;
+
+ [SetUp]
+ public void Init ()
+ {
+ repositories = new List<IPackageRepository> ();
+ }
+
+ FakePackageRepository AddRepository ()
+ {
+ var repository = new FakePackageRepository ();
+ repositories.Add (repository);
+ return repository;
+ }
+
+ FakePackage AddRepositoryWithOnePackage (string packageId)
+ {
+ FakePackageRepository repository = AddRepository ();
+ return repository.AddFakePackage (packageId);
+ }
+
+ void CreateAggregateRepository ()
+ {
+ aggregateRepository = new MonoDevelopAggregateRepository (repositories);
+ aggregateRepository.IgnoreFailingRepositories = true;
+ }
+
+ ExceptionThrowingPackageRepository AddFailingPackageRepository ()
+ {
+ return AddFailingPackageRepository (new Exception ("Error"));
+ }
+
+ ExceptionThrowingPackageRepository AddFailingPackageRepository (Exception exception)
+ {
+ var repository = new ExceptionThrowingPackageRepository {
+ GetPackagesException = exception
+ };
+ repositories.Add (repository);
+ return repository;
+ }
+
+ List<IPackage> Search ()
+ {
+ return aggregateRepository.Search (null, false).ToList ();
+ }
+
+ [Test]
+ public void Search_IgnoreFailingRepositoriesAndOnePackageSourceFails_ErrorFromFailingRepositoryIsSupressed ()
+ {
+ FakePackage package1 = AddRepositoryWithOnePackage ("Package1");
+ FakePackage package2 = AddRepositoryWithOnePackage ("Package2");
+ AddFailingPackageRepository ();
+ CreateAggregateRepository ();
+ aggregateRepository.IgnoreFailingRepositories = true;
+
+ List<IPackage> packages = Search ();
+
+ Assert.AreEqual (2, packages.Count);
+ Assert.That (packages, Contains.Item (package1));
+ Assert.That (packages, Contains.Item (package2));
+ }
+
+ [Test]
+ public void Search_TwoPackageRepositoriesOneFailingWhenGetPackagesCalled_AnyFailuresReturnsTrueAndAllFailedReturnsFalse ()
+ {
+ AddRepository ();
+ AddFailingPackageRepository ();
+ CreateAggregateRepository ();
+ Search ();
+
+ bool failures = aggregateRepository.AnyFailures ();
+ bool allFailed = aggregateRepository.AllFailed ();
+
+ Assert.IsTrue (failures);
+ Assert.IsFalse (allFailed);
+ }
+
+ [Test]
+ public void Search_TwoPackageRepositoriesBothFailingWhenGetPackagesCalled_AllFailedReturnsTrue ()
+ {
+ AddFailingPackageRepository ();
+ AddFailingPackageRepository ();
+ CreateAggregateRepository ();
+ Search ();
+
+ bool failures = aggregateRepository.AnyFailures ();
+ bool allFailed = aggregateRepository.AllFailed ();
+
+ Assert.IsTrue (failures);
+ Assert.IsTrue (allFailed);
+ }
+
+ [Test]
+ public void Search_TwoPackageRepositoriesNoneFailingWhenGetPackagesCalled_AnyFailuresAndAllFailedReturnFalse ()
+ {
+ AddRepository ();
+ AddRepository ();
+ CreateAggregateRepository ();
+ Search ();
+
+ bool failures = aggregateRepository.AnyFailures ();
+ bool allFailed = aggregateRepository.AllFailed ();
+
+ Assert.IsFalse (failures);
+ Assert.IsFalse (allFailed);
+ }
+
+ [Test]
+ public void Search_TwoPackageRepositoriesOneFailingWhenGetPackagesCalled_GetAggregateExceptionIncludesRepositoryException ()
+ {
+ AddRepository ();
+ var exception = new Exception ("Error");
+ AddFailingPackageRepository (exception);
+ CreateAggregateRepository ();
+ Search ();
+
+ AggregateException aggregateException = aggregateRepository.GetAggregateException ();
+
+ Assert.That (aggregateException.InnerExceptions, Contains.Item (exception));
+ }
+
+ [Test]
+ public void Search_TwoPackageRepositoriesBothFailingWhenGetPackagesCalled_GetAggregateExceptionIncludesBothRepositoryExceptions ()
+ {
+ var exception1 = new Exception ("Error1");
+ AddFailingPackageRepository (exception1);
+ var exception2 = new Exception ("Error2");
+ AddFailingPackageRepository (exception2);
+ CreateAggregateRepository ();
+ Search ();
+
+ AggregateException aggregateException = aggregateRepository.GetAggregateException ();
+
+ Assert.That (aggregateException.InnerExceptions, Contains.Item (exception1));
+ Assert.That (aggregateException.InnerExceptions, Contains.Item (exception2));
+ }
+
+ [Test]
+ public void Search_TwoPackageRepositoriesBothFailingWhenGetPackagesCalledFirstThenSecondTimeNewRepositoryAddedToRepositories_AllFailedReturnsFalseSecondTime ()
+ {
+ AddFailingPackageRepository ();
+ AddFailingPackageRepository ();
+ CreateAggregateRepository ();
+ Search ();
+ AddRepository ();
+
+ bool failures = aggregateRepository.AnyFailures ();
+ bool allFailed = aggregateRepository.AllFailed ();
+
+ Assert.IsTrue (failures);
+ Assert.IsFalse (allFailed);
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/NuGetPackageRestoreCommandLineTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/NuGetPackageRestoreCommandLineTests.cs deleted file mode 100644 index 47154fcf57..0000000000 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/NuGetPackageRestoreCommandLineTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -//
-// NuGetPackageRestoreCommandLineTests.cs
-//
-// Author:
-// Matt Ward <matt.ward@xamarin.com>
-//
-// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-using System;
-using ICSharpCode.PackageManagement;
-using NUnit.Framework;
-using MonoDevelop.Core.Assemblies;
-using MonoDevelop.PackageManagement.Tests.Helpers;
-using System.IO;
-
-namespace MonoDevelop.PackageManagement.Tests
-{
- [TestFixture]
- public class NuGetPackageRestoreCommandLineTests
- {
- NuGetPackageRestoreCommandLine commandLine;
-
- void CreateCommandLineWithSolution (string fileName)
- {
- CreateCommandLineWithSolution (fileName, null, false);
- }
-
- void CreateCommandLineWithSolution (string fileName, MonoRuntimeInfo monoRuntimeInfo)
- {
- CreateCommandLineWithSolution (fileName, monoRuntimeInfo, true);
- }
-
- void CreateCommandLineWithSolution (string fileName, MonoRuntimeInfo monoRuntimeInfo, bool isMonoRuntime)
- {
- var solution = new FakePackageManagementSolution ();
- solution.FileName = fileName;
- commandLine = new NuGetPackageRestoreCommandLine (
- solution,
- monoRuntimeInfo,
- isMonoRuntime);
- }
-
- [Test]
- public void Arguments_RestoreSolution_SolutionFullFileNameUsed ()
- {
- CreateCommandLineWithSolution (@"d:\projects\MySolution\MySolution.sln");
-
- string arguments = commandLine.Arguments;
-
- string expectedArguments = "restore -NonInteractive \"d:\\projects\\MySolution\\MySolution.sln\"";
- Assert.AreEqual (expectedArguments, arguments);
- }
-
- [Test]
- public void CommandLine_RestoreSolutionOnMono_MonoUsedFromCurrentPrefix ()
- {
- var monoRuntime = new MonoRuntimeInfo (@"c:\Users\Prefix");
- CreateCommandLineWithSolution (@"d:\projects\MySolution\MySolution.sln", monoRuntime);
-
- string arguments = commandLine.Arguments;
-
- string expectedCommandLine = Path.Combine (@"c:\Users\Prefix", "bin", "mono");
- Assert.IsTrue (arguments.StartsWith ("--runtime=v4.0 "), arguments);
- Assert.IsTrue (arguments.EndsWith ("restore -NonInteractive \"d:\\projects\\MySolution\\MySolution.sln\""), arguments);
- Assert.AreEqual (expectedCommandLine, commandLine.Command);
- }
- }
-}
\ No newline at end of file diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementProjectTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementProjectTests.cs index cf3356d5b5..bad7bed11b 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementProjectTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementProjectTests.cs @@ -818,6 +818,28 @@ namespace MonoDevelop.PackageManagement.Tests Assert.IsTrue (result);
}
+
+ [Test]
+ public void ConstraintProvider_LocalRepositoryDoesNotImplementIConstraintProvider_ReturnsNullConstraintProviderInstance ()
+ {
+ CreateProject ();
+
+ IPackageConstraintProvider provider = project.ConstraintProvider;
+
+ Assert.AreEqual (NullConstraintProvider.Instance, provider);
+ }
+
+ [Test]
+ public void ConstraintProvider_LocalRepositoryImplementsIConstraintProvider_ReturnsLocalRepository ()
+ {
+ CreateProject ();
+ var localRepository = new FakePackageRepositoryWithConstraintProvider ();
+ fakeProjectManager.FakeLocalRepository = localRepository;
+
+ IPackageConstraintProvider provider = project.ConstraintProvider;
+
+ Assert.AreEqual (localRepository, provider);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementSolutionTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementSolutionTests.cs index 5a640acf0e..d7d5b380ca 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementSolutionTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageManagementSolutionTests.cs @@ -699,6 +699,20 @@ namespace MonoDevelop.PackageManagement.Tests var expectedPackages = new FakePackage [0];
Assert.AreEqual (expectedPackages, packages);
}
+
+ [Test]
+ public void GetRepository_OpenSolution_ReturnsRepositoryForSolution ()
+ {
+ CreateSolution ();
+ var fakeSolution = new FakeSolution (@"d:\projects\MyProject\MySolution.sln");
+ fakeProjectService.OpenSolution = fakeSolution;
+
+ ISolutionPackageRepository repository = solution.GetRepository ();
+
+ Assert.IsNotNull (repository);
+ Assert.AreEqual (fakeSolutionPackageRepositoryFactory.SolutionPassedToCreateSolutionPackageRepository, fakeSolution);
+ Assert.AreEqual (fakeSolutionPackageRepositoryFactory.FakeSolutionPackageRepository, repository);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageReferenceNodeTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageReferenceNodeTests.cs index 34e246d9c5..3f7609c3d1 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageReferenceNodeTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageReferenceNodeTests.cs @@ -30,6 +30,7 @@ using NUnit.Framework; using NuGet;
using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
+using MonoDevelop.Ide.Tasks;
namespace MonoDevelop.PackageManagement.Tests
{
@@ -85,25 +86,36 @@ namespace MonoDevelop.PackageManagement.Tests }
[Test]
- public void GetLabel_PackageReferenceIsNotInstalled_ReturnsPackageIdInsideErrorColouredSpan ()
+ public void GetLabel_PackageReferenceIsNotInstalled_ReturnsPackageId ()
{
CreatePackageReference (packageId: "MyPackage");
CreatePackageReferenceNode (installed: false);
string label = node.GetLabel ();
- Assert.AreEqual ("<span color='#c99c00'>MyPackage</span>", label);
+ Assert.AreEqual ("MyPackage", label);
}
[Test]
- public void GetLabel_PackageReferenceNeedsReinstallation_ReturnsPackageIdInsideErrorColouredSpan ()
+ public void GetLabel_PackageReferenceNeedsReinstallation_ReturnsPackageId ()
{
CreatePackageReference (packageId: "MyPackage", requireReinstallation: true);
CreatePackageReferenceNode (installed: true);
string label = node.GetLabel ();
- Assert.AreEqual ("<span color='#c99c00'>MyPackage</span>", label);
+ Assert.AreEqual ("MyPackage", label);
+ }
+
+ [Test]
+ public void GetLabel_PackageReferenceIsPendingInstall_ReturnsPackageIdFollowedByInstallingText ()
+ {
+ CreatePackageReference (packageId: "MyPackage");
+ CreatePackageReferenceNode (installed: false, installPending: true);
+
+ string label = node.GetLabel ();
+
+ Assert.AreEqual ("MyPackage (installing)", label);
}
[Test]
@@ -118,14 +130,14 @@ namespace MonoDevelop.PackageManagement.Tests }
[Test]
- public void GetIconId_PackageReferenceNeedsReinstallation_ReturnsReferenceWarningIcon ()
+ public void GetIconId_PackageReferenceNeedsReinstallation_ReturnsReferenceIcon ()
{
CreatePackageReference (requireReinstallation: true);
CreatePackageReferenceNode ();
IconId icon = node.GetIconId ();
- Assert.AreEqual (Stock.ReferenceWarning, icon);
+ Assert.AreEqual (Stock.Reference, icon);
}
[Test]
@@ -140,7 +152,7 @@ namespace MonoDevelop.PackageManagement.Tests }
[Test]
- public void GetLabel_PackageReferenceNeedsReinstallationButHasUpdate_ReturnsPackageIdInsideErrorColouredSpanAndUpdatedPackageVersionInGreySpan ()
+ public void GetLabel_PackageReferenceNeedsReinstallationButHasUpdate_ReturnsPackageIdInBlackTextAndUpdatedPackageVersionInGreySpan ()
{
CreatePackageReference (
packageId: "MyPackage",
@@ -151,7 +163,128 @@ namespace MonoDevelop.PackageManagement.Tests string label = node.GetLabel ();
- Assert.AreEqual ("<span color='#c99c00'>MyPackage</span> <span color='grey'>(1.2.3.4 available)</span>", label);
+ Assert.AreEqual ("MyPackage <span color='grey'>(1.2.3.4 available)</span>", label);
+ }
+
+ [Test]
+ public void IsDisabled_PackageReferenceHasInstallPending_ReturnsTrue ()
+ {
+ CreatePackageReference ();
+ CreatePackageReferenceNode (installed: false, installPending: true);
+
+ bool result = node.IsDisabled ();
+
+ Assert.IsTrue (result);
+ }
+
+ [Test]
+ public void IsDisabled_PackageReferenceIsInstalled_ReturnsFalse ()
+ {
+ CreatePackageReference ();
+ CreatePackageReferenceNode ();
+
+ bool result = node.IsDisabled ();
+
+ Assert.IsFalse (result);
+ }
+
+ [Test]
+ public void IsDisabled_PackageReferenceIsNotInstalled_ReturnsTrue ()
+ {
+ CreatePackageReference (packageId: "MyPackage");
+ CreatePackageReferenceNode (installed: false);
+
+ bool result = node.IsDisabled ();
+
+ Assert.IsTrue (result);
+ }
+
+ [Test]
+ public void GetStatusSeverity_PackageReferenceIsInstalled_ReturnsNull ()
+ {
+ CreatePackageReference ();
+ CreatePackageReferenceNode ();
+
+ TaskSeverity? status = node.GetStatusSeverity ();
+
+ Assert.IsNull (status);
+ }
+
+ [Test]
+ public void GetStatusSeverity_PackageReferenceIsNotInstalled_ReturnsWarning ()
+ {
+ CreatePackageReference (packageId: "MyPackage");
+ CreatePackageReferenceNode (installed: false);
+
+ TaskSeverity? status = node.GetStatusSeverity ();
+
+ Assert.AreEqual (TaskSeverity.Warning, status);
+ }
+
+ [Test]
+ public void GetStatusSeverity_PackageReferenceNeedsReinstallation_ReturnsWarning ()
+ {
+ CreatePackageReference (requireReinstallation: true);
+ CreatePackageReferenceNode ();
+
+ TaskSeverity? status = node.GetStatusSeverity ();
+
+ Assert.AreEqual (TaskSeverity.Warning, status);
+ }
+
+ [Test]
+ public void GetStatusSeverity_PackageReferenceHasInstallPending_ReturnsNull ()
+ {
+ CreatePackageReference ();
+ CreatePackageReferenceNode (installed: false, installPending: true);
+
+ TaskSeverity? status = node.GetStatusSeverity ();
+
+ Assert.IsNull (status);
+ }
+
+ [Test]
+ public void GetStatusMessage_PackageReferenceIsInstalled_ReturnsNull ()
+ {
+ CreatePackageReference ();
+ CreatePackageReferenceNode ();
+
+ string message = node.GetStatusMessage ();
+
+ Assert.IsNull (message);
+ }
+
+ [Test]
+ public void GetStatusMessage_PackageReferenceIsNotInstalled_ReturnsPackageNotRestoredMessage ()
+ {
+ CreatePackageReference (packageId: "MyPackage");
+ CreatePackageReferenceNode (installed: false);
+
+ string message = node.GetStatusMessage ();
+
+ Assert.AreEqual ("Package is not restored", message);
+ }
+
+ [Test]
+ public void GetStatusMessage_PackageReferenceNeedsReinstallation_ReturnsPackageNeedsRetargetingMessage ()
+ {
+ CreatePackageReference (requireReinstallation: true);
+ CreatePackageReferenceNode ();
+
+ string message = node.GetStatusMessage ();
+
+ Assert.AreEqual ("Package needs retargeting", message);
+ }
+
+ [Test]
+ public void GetStatusMessage_PackageReferenceHasInstallPending_ReturnsNull ()
+ {
+ CreatePackageReference ();
+ CreatePackageReferenceNode (installed: false, installPending: true);
+
+ string message = node.GetStatusMessage ();
+
+ Assert.IsNull (message);
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageRepositoryCacheTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageRepositoryCacheTests.cs index 8520911df4..6c02e947bc 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageRepositoryCacheTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageRepositoryCacheTests.cs @@ -43,6 +43,7 @@ namespace MonoDevelop.PackageManagement.Tests OneRegisteredPackageSourceHelper packageSourcesHelper;
RecentPackageInfo[] recentPackagesPassedToCreateRecentPackageRepository;
FakePackageRepository fakeAggregateRepositoryPassedToCreateRecentPackageRepository;
+ FakePackageRepository machineCache;
void CreateCache ()
{
@@ -57,9 +58,15 @@ namespace MonoDevelop.PackageManagement.Tests void CreateCacheUsingPackageSources ()
{
- nuGetPackageSource = new PackageSource ("http://nuget.org", "NuGet");
fakePackageRepositoryFactory = new FakePackageRepositoryFactory ();
- cache = new PackageRepositoryCache (packageSourcesHelper.Options, fakePackageRepositoryFactory);
+ CreateCacheUsingPackageSources (fakePackageRepositoryFactory);
+ }
+
+ void CreateCacheUsingPackageSources (ISharpDevelopPackageRepositoryFactory repositoryFactory)
+ {
+ nuGetPackageSource = new PackageSource ("http://nuget.org", "NuGet");
+ machineCache = new FakePackageRepository ();
+ cache = new PackageRepositoryCache (packageSourcesHelper.Options, machineCache, repositoryFactory);
}
FakePackageRepository AddFakePackageRepositoryForPackageSource (string source)
@@ -409,6 +416,70 @@ namespace MonoDevelop.PackageManagement.Tests CollectionAssert.AreEqual (expectedInitialRepositories, actualInitialRepositories);
CollectionAssert.AreEqual (expectedRepositories, actualRepositories);
}
+
+ [Test]
+ public void CreateAggregatePriorityRepository_NoAggregatePackageSources_ReturnsPriorityPackageRepositoryThatUsesMachineCache ()
+ {
+ CreateCache ();
+ machineCache.AddFakePackageWithVersion ("MyPackage", "1.0");
+
+ IPackageRepository repository = cache.CreateAggregateWithPriorityMachineCacheRepository ();
+ bool exists = repository.Exists ("MyPackage", new SemanticVersion ("1.0"));
+
+ Assert.IsInstanceOf<PriorityPackageRepository> (repository);
+ Assert.IsTrue (exists);
+ }
+
+ [Test]
+ public void CreateAggregatePriorityRepository_NoAggregatePackageSources_ReturnsPriorityPackageRepositoryThatUsesAggregateRepository ()
+ {
+ CreatePackageSources ();
+ packageSourcesHelper.AddTwoPackageSources ("Source1", "Source2");
+ CreateCacheUsingPackageSources ();
+ fakePackageRepositoryFactory.FakeAggregateRepository.AddFakePackageWithVersion ("MyPackage", "1.0");
+
+ IPackageRepository repository = cache.CreateAggregateWithPriorityMachineCacheRepository ();
+ bool exists = repository.Exists ("MyPackage", new SemanticVersion ("1.0"));
+
+ Assert.IsTrue (exists);
+ }
+
+ [Test]
+ public void CreateAggregateRepository_OnePackageSourceHasInvalidUri_NoExceptionThrownWhenCreatingAggregateRepositoryAndSearchingForPackages ()
+ {
+ CreatePackageSources ();
+ packageSourcesHelper.RegisteredPackageSources.Clear ();
+ var invalidPackageSource = new PackageSource (String.Empty, "InvalidSource");
+ packageSourcesHelper.RegisteredPackageSources.Add (invalidPackageSource);
+ var factory = new SharpDevelopPackageRepositoryFactory ();
+ CreateCacheUsingPackageSources (factory);
+ IPackageRepository repository = cache.CreateAggregateRepository ();
+ var aggregateRepository = (MonoDevelopAggregateRepository)repository;
+
+ Assert.IsFalse (aggregateRepository.AnyFailures ());
+ Assert.DoesNotThrow (() => repository.Search ("abc", false));
+ Assert.IsTrue (aggregateRepository.AnyFailures ());
+ }
+
+ [Test]
+ public void CreateAggregateRepository_OnePackageSourceHasInvalidUriAndSearchExecutedMultipleTimes_ExceptionThrownByPackageRepositoryIsOnlyRecordedOnce ()
+ {
+ CreatePackageSources ();
+ packageSourcesHelper.RegisteredPackageSources.Clear ();
+ var invalidPackageSource = new PackageSource (String.Empty, "InvalidSource");
+ packageSourcesHelper.RegisteredPackageSources.Add (invalidPackageSource);
+ var factory = new SharpDevelopPackageRepositoryFactory ();
+ CreateCacheUsingPackageSources (factory);
+ IPackageRepository repository = cache.CreateAggregateRepository ();
+ var aggregateRepository = (MonoDevelopAggregateRepository)repository;
+
+ repository.Search ("abc", false);
+ repository.Search ("abc", false);
+ repository.Search ("abc", false);
+
+ Assert.IsTrue (aggregateRepository.AnyFailures ());
+ Assert.AreEqual (1, aggregateRepository.GetAggregateException ().InnerExceptions.Count);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageViewModelTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageViewModelTests.cs index 9b0fffb681..b406395815 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageViewModelTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackageViewModelTests.cs @@ -60,7 +60,7 @@ namespace MonoDevelop.PackageManagement.Tests void CreateViewModel (FakePackageManagementSolution solution)
{
- viewModelParent = CreateViewModelParent ();
+ viewModelParent = CreateViewModelParent (solution);
viewModel = new TestablePackageViewModel (viewModelParent, solution);
fakePackage = viewModel.FakePackage;
this.fakeSolution = solution;
@@ -69,7 +69,7 @@ namespace MonoDevelop.PackageManagement.Tests fakeUninstallPackageAction = solution.FakeProjectToReturnFromGetProject.FakeUninstallPackageAction;
}
- AvailablePackagesViewModel CreateViewModelParent ()
+ AvailablePackagesViewModel CreateViewModelParent (FakePackageManagementSolution solution)
{
var taskFactory = new FakeTaskFactory ();
var registeredPackageRepositories = new FakeRegisteredPackageRepositories ();
@@ -77,6 +77,7 @@ namespace MonoDevelop.PackageManagement.Tests var recentPackageRepository = new FakeRecentPackageRepository ();
return new AvailablePackagesViewModel (
+ solution,
registeredPackageRepositories,
recentPackageRepository,
packageViewModelFactory,
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackagesViewModelTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackagesViewModelTests.cs index 57c1db3c49..1dd3518bb4 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackagesViewModelTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/PackagesViewModelTests.cs @@ -941,7 +941,7 @@ namespace MonoDevelop.PackageManagement.Tests viewModel.ReadPackages ();
- PackagesForSelectedPageResult result = taskFactory.FirstFakeTaskCreated.ExecuteTaskButNotContinueWith ();
+ taskFactory.FirstFakeTaskCreated.ExecuteTaskButNotContinueWith ();
Assert.IsFalse (viewModel.IsPaged);
}
@@ -1420,7 +1420,7 @@ namespace MonoDevelop.PackageManagement.Tests public void CheckedPackageViewModels_OnePackageIsCheckedAndThenUnchecked_ReturnsNoCheckedPackages ()
{
CreateViewModel ();
- FakePackage package = viewModel.AddFakePackage ("MyPackage");
+ viewModel.AddFakePackage ("MyPackage");
viewModel.AddFakePackage ("Z-Package");
viewModel.ReadPackages ();
CompleteReadPackagesTask ();
@@ -1537,5 +1537,24 @@ namespace MonoDevelop.PackageManagement.Tests PackageCollectionAssert.AreEqual (expectedPackages, viewModel.CheckedPackageViewModels);
Assert.IsFalse (oldPackageVersionViewModel.IsChecked);
}
+
+ [Test]
+ public void ReadPackages_ReadPackagesCalledAgainAfterFirstOneFailed_ErrorIsCleared ()
+ {
+ CreateViewModel ();
+ viewModel.ReadPackages ();
+ var ex = new Exception ("Test");
+ var aggregateEx = new AggregateException (ex);
+ taskFactory.FirstFakeTaskCreated.Exception = aggregateEx;
+ taskFactory.FirstFakeTaskCreated.IsFaulted = true;
+ CompleteReadPackagesTask ();
+ bool hasErrorAfterFirstRead = viewModel.HasError;
+
+ viewModel.ReadPackages ();
+
+ Assert.IsTrue (hasErrorAfterFirstRead);
+ Assert.IsFalse (viewModel.HasError);
+ Assert.AreEqual (String.Empty, viewModel.ErrorMessage);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ProjectPackagesFolderNodeTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ProjectPackagesFolderNodeTests.cs index d040d29175..844fe26dc4 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ProjectPackagesFolderNodeTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ProjectPackagesFolderNodeTests.cs @@ -169,7 +169,7 @@ namespace MonoDevelop.PackageManagement.Tests PackageReferenceNode referenceNode = nodes.FirstOrDefault ();
Assert.AreEqual (1, nodes.Count);
Assert.IsFalse (referenceNode.Installed);
- Assert.AreEqual ("<span color='#c99c00'>MyPackage</span>", referenceNode.GetLabel ());
+ Assert.AreEqual ("MyPackage", referenceNode.GetLabel ());
}
[Test]
@@ -192,7 +192,7 @@ namespace MonoDevelop.PackageManagement.Tests public void GetPackageReferencesNodes_OnePackageReferenceWithUpdatedPackagesButPackageNotRestored_ReturnsOneNodeWithUpdatedVersionInformationInLabel ()
{
CreateNode ();
- PackageReference packageReference = AddPackageReferenceToProject ("MyPackage", "1.0");
+ AddPackageReferenceToProject ("MyPackage", "1.0");
AddUpdatedPackageForProject ("MyPackage", "1.2");
List<PackageReferenceNode> nodes = packagesFolderNode.GetPackageReferencesNodes ().ToList ();
@@ -200,8 +200,9 @@ namespace MonoDevelop.PackageManagement.Tests PackageReferenceNode referenceNode = nodes.FirstOrDefault ();
Assert.AreEqual (1, nodes.Count);
Assert.AreEqual ("1.2", referenceNode.UpdatedVersion.ToString ());
- Assert.AreEqual ("<span color='#c99c00'>MyPackage</span> <span color='grey'>(1.2 available)</span>", referenceNode.GetLabel ());
- Assert.AreEqual (Stock.ReferenceWarning, referenceNode.GetIconId ());
+ Assert.AreEqual ("MyPackage <span color='grey'>(1.2 available)</span>", referenceNode.GetLabel ());
+ Assert.AreEqual (Stock.Reference, referenceNode.GetIconId ());
+ Assert.IsTrue (referenceNode.IsDisabled ());
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RecentPackageRepositoryTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RecentPackageRepositoryTests.cs index 52f8577756..ab9d358517 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RecentPackageRepositoryTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RecentPackageRepositoryTests.cs @@ -212,5 +212,20 @@ namespace MonoDevelop.PackageManagement.Tests Assert.IsTrue (hasRecentPackages);
}
+
+ [Test]
+ public void GetPackages_TwoRecentPackagesButOneIsInvalid_OnlyValidPackageIsReturned ()
+ {
+ CreateRepository ();
+ FakePackage package1 = AddOnePackageToRepository ("Test1");
+ FakePackage package2 = AddOnePackageToRepository ("Test2");
+ package2.IsValid = false;
+
+ var expectedPackages = new IPackage[] {
+ package1
+ };
+
+ PackageCollectionAssert.AreEqual (expectedPackages, repository.GetPackages ());
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RegisteredPackageRepositoriesTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RegisteredPackageRepositoriesTests.cs index 1986c835e6..9cf27599b3 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RegisteredPackageRepositoriesTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RegisteredPackageRepositoriesTests.cs @@ -25,6 +25,7 @@ // THE SOFTWARE.
using System;
+using System.Linq;
using ICSharpCode.PackageManagement;
using MonoDevelop.PackageManagement.Tests.Helpers;
using NuGet;
@@ -56,6 +57,17 @@ namespace MonoDevelop.PackageManagement.Tests registeredRepositories = new RegisteredPackageRepositories (fakeRepositoryCache, packageSourcesHelper.Options);
}
+ void AddPackageSourcesToSettings (params string[] sources)
+ {
+ var packageSources = sources.Select (source => new PackageSource (source));
+ packageSourcesHelper.FakeSettings.AddFakePackageSources (packageSources);
+ }
+
+ void SetActivePackageSourceInSettings (PackageSource packageSource)
+ {
+ packageSourcesHelper.FakeSettings.SetFakeActivePackageSource (packageSource);
+ }
+
[Test]
public void RecentPackageRepository_PropertyAccessed_ReturnsRecentPackageRepositoryFromCache ()
{
@@ -309,6 +321,48 @@ namespace MonoDevelop.PackageManagement.Tests Assert.IsNull (activePackageSource);
}
+
+ [Test]
+ public void UpdatePackageSources_SolutionLoadedAggregatePackageSourceIsActiveThenAllSourcesDisabledApartFromOne_ActivePackageSourceIsNotAggregatePackageSource ()
+ {
+ CreateRegisteredPackageRepositories ();
+ packageSourcesHelper.AddTwoPackageSources ("One", "Two");
+ var expectedPackageSource = new PackageSource ("Two") { IsEnabled = true };
+ var updatedPackageSources = new PackageSource [] {
+ new PackageSource ("One") { IsEnabled = false },
+ expectedPackageSource
+ };
+ AddPackageSourcesToSettings ("One", "Two");
+ SetActivePackageSourceInSettings (RegisteredPackageSourceSettings.AggregatePackageSource);
+ packageSourcesHelper.Options.ProjectService.RaiseSolutionLoadedEvent ();
+ registeredRepositories.ActivePackageSource = RegisteredPackageSourceSettings.AggregatePackageSource;
+
+ registeredRepositories.UpdatePackageSources (updatedPackageSources);
+
+ Assert.AreEqual (expectedPackageSource, registeredRepositories.ActivePackageSource);
+ }
+
+ [Test]
+ public void UpdatePackageSources_PackageSourcesUpdatedInPreferencesWhenAggregatePackageSourceIsActive_ActiveRepositoryIsRecreated ()
+ {
+ CreateRegisteredPackageRepositories ();
+ packageSourcesHelper.AddTwoPackageSources ("One", "Two");
+ var updatedPackageSources = new PackageSource [] {
+ new PackageSource ("One"),
+ new PackageSource ("Two")
+ };
+ AddPackageSourcesToSettings ("One", "Two");
+ SetActivePackageSourceInSettings (RegisteredPackageSourceSettings.AggregatePackageSource);
+ registeredRepositories.ActivePackageSource = RegisteredPackageSourceSettings.AggregatePackageSource;
+ IPackageRepository firstAggregateRepository = registeredRepositories.ActiveRepository;
+ fakeRepositoryCache.FakeAggregateRepository = new FakePackageRepository ();
+
+ registeredRepositories.UpdatePackageSources (updatedPackageSources);
+ IPackageRepository secondAggregateRepository = registeredRepositories.ActiveRepository;
+
+ Assert.AreNotSame (firstAggregateRepository, secondAggregateRepository);
+ Assert.AreSame (secondAggregateRepository, fakeRepositoryCache.FakeAggregateRepository);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallPackageActionTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallPackageActionTests.cs index 959e514b3c..a29f34d06c 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallPackageActionTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallPackageActionTests.cs @@ -42,7 +42,7 @@ namespace MonoDevelop.PackageManagement.Tests void CreateAction (string packageId = "MyPackage", string packageVersion = "1.2.3.4")
{
project = new FakePackageManagementProject ();
- FakePackageOperation operation = project.AddFakeInstallOperation ();
+ project.AddFakeInstallOperation ();
packageManagementEvents = new PackageManagementEvents ();
@@ -84,7 +84,7 @@ namespace MonoDevelop.PackageManagement.Tests public void Execute_PackageExistsInSourceRepository_PackageIsForcefullyRemovedSoItDoesNotFailIfOtherPackagesDependOnIt ()
{
CreateAction ("MyPackage", "1.2.3.4");
- FakePackage package = AddPackageToSourceRepository ("MyPackage", "1.2.3.4");
+ AddPackageToSourceRepository ("MyPackage", "1.2.3.4");
action.Execute ();
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallProjectPackagesActionTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallProjectPackagesActionTests.cs index 2ec6b28ac3..61ff6616d5 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallProjectPackagesActionTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/ReinstallProjectPackagesActionTests.cs @@ -152,9 +152,9 @@ namespace MonoDevelop.PackageManagement.Tests {
CreateAction ();
AddPackageToProject ("MyPackage", "1.0");
- FakePackage sourceRepositoryPackage = AddPackageToSourceRepository ("MyPackage", "1.0");
+ AddPackageToSourceRepository ("MyPackage", "1.0");
var expectedPackages = new FakePackage[] { FakePackage.CreatePackageWithVersion ("MyPackage", "1.0") };
- ReinstallPackageOperations operations = AddReinstallOperationsToProject (expectedPackages);
+ AddReinstallOperationsToProject (expectedPackages);
action.Execute ();
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RestorePackagesActionTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RestorePackagesActionTests.cs new file mode 100644 index 0000000000..f247203e80 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/RestorePackagesActionTests.cs @@ -0,0 +1,322 @@ +//
+// RestorePackagesAction.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.PackageManagement;
+using MonoDevelop.PackageManagement.Tests.Helpers;
+using NUnit.Framework;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement.Tests
+{
+ [TestFixture]
+ public class RestorePackagesActionTests
+ {
+ RestorePackagesAction action;
+ FakePackageManagementSolution solution;
+ FakePackageManagerFactory packageManagerFactory;
+ FakePackageRepositoryFactory packageRepositoryCache;
+ PackageManagementEvents packageEvents;
+ List<PackageOperationMessage> messagesLogged;
+
+ void CreateSolution ()
+ {
+ packageManagerFactory = new FakePackageManagerFactory ();
+ packageRepositoryCache = new FakePackageRepositoryFactory ();
+ packageEvents = new PackageManagementEvents ();
+ solution = new FakePackageManagementSolution ();
+ }
+
+ FakePackageManagementProject CreateSolutionWithOneProject ()
+ {
+ CreateSolution ();
+ return solution.AddFakeProject ("MyProject");
+ }
+
+ void CreateAction ()
+ {
+ action = new RestorePackagesAction (
+ solution,
+ packageEvents,
+ packageRepositoryCache,
+ packageManagerFactory);
+ }
+
+ FakePackage AddPackageToPriorityRepository (string packageId, string packageVersion)
+ {
+ return packageRepositoryCache
+ .FakePriorityPackageRepository
+ .AddFakePackageWithVersion (packageId, packageVersion);
+ }
+
+ void CaptureMessagesLogged ()
+ {
+ messagesLogged = new List<PackageOperationMessage> ();
+ packageEvents.PackageOperationMessageLogged += (sender, e) => {
+ messagesLogged.Add (e.Message);
+ };
+ }
+
+ FakeOperationAwarePackageRepository MakePriorityRepositoryOperationAware ()
+ {
+ var repository = new FakeOperationAwarePackageRepository ();
+ packageRepositoryCache.FakePriorityPackageRepository = repository;
+ return repository;
+ }
+
+ void PackageIsRestored (FakePackage package)
+ {
+ solution.SolutionPackageRepository.FakePackages.Add (package);
+ }
+
+ void AssertMessageLogged (string expectedMessage)
+ {
+ List<string> allMessages = messagesLogged.Select (message => message.ToString ()).ToList ();
+ Assert.That (allMessages, Contains.Item (expectedMessage));
+ }
+
+ void AssertMessageIsNotLogged (string expectedMessage)
+ {
+ List<string> allMessages = messagesLogged.Select (message => message.ToString ()).ToList ();
+ Assert.That (allMessages, Has.No.Contains (expectedMessage));
+ }
+
+ void AssertNoMessageLoggedThatContains (string expectedMessage)
+ {
+ List<string> allMessages = messagesLogged.Select (message => message.ToString ()).ToList ();
+ Assert.That (allMessages, Has.No.ContainsSubstring (expectedMessage));
+ }
+
+ [Test]
+ public void Execute_ProjectHasOneUnrestoredPackage_PackageFromPriorityRepositoryIsInstalled ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.0");
+ FakePackage package = AddPackageToPriorityRepository ("MyPackage", "1.0");
+ CreateAction ();
+
+ action.Execute ();
+
+ Assert.AreEqual (package, packageManagerFactory.FakePackageManager.PackagePassedToInstallPackage);
+ Assert.IsTrue (packageManagerFactory.FakePackageManager.IgnoreWalkInfoPassedToInstallPackage);
+ Assert.IsTrue (packageManagerFactory.FakePackageManager.IgnoreDependenciesPassedToInstallPackage);
+ Assert.IsTrue (packageManagerFactory.FakePackageManager.AllowPrereleaseVersionsPassedToInstallPackage);
+ Assert.AreEqual (packageRepositoryCache.FakePriorityPackageRepository, packageManagerFactory.PackageRepositoryPassedToCreatePackageManager);
+ Assert.AreEqual (solution.SolutionPackageRepository, packageManagerFactory.SolutionPackageRepositoryPassedToCreatePackageManager);
+ }
+
+ [Test]
+ public void Execute_ProjectHasOneUnrestoredPackage_PackageManagerHasLoggerConfigured ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.0");
+ AddPackageToPriorityRepository ("MyPackage", "1.0");
+ CreateAction ();
+
+ action.Execute ();
+
+ Assert.IsInstanceOf<PackageManagementLogger> (packageManagerFactory.FakePackageManager.Logger);
+ }
+
+ [Test]
+ public void Execute_ProjectHasOneUnrestoredPackage_RestoringPackagesMessageLogged ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.0");
+ AddPackageToPriorityRepository ("MyPackage", "1.0");
+ CreateAction ();
+ CaptureMessagesLogged ();
+
+ action.Execute ();
+
+ Assert.AreEqual ("Restoring packages...", messagesLogged [0].ToString ());
+ }
+
+ [Test]
+ public void Execute_ProjectHasOneUnrestoredPackage_RestoreOperationAddedToHttpHeader ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.0");
+ FakeOperationAwarePackageRepository repository = MakePriorityRepositoryOperationAware ();
+ AddPackageToPriorityRepository ("MyPackage", "1.0");
+ CreateAction ();
+
+ action.Execute ();
+
+ repository.AssertOperationWasStartedAndDisposed (
+ RepositoryOperationNames.Restore,
+ "MyPackage",
+ "1.0");
+ }
+
+ [Test]
+ public void Execute_ProjectHasOnePackageWhichIsRestored_PackageIsNotInstalledAgain ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.0");
+ FakePackage package = AddPackageToPriorityRepository ("MyPackage", "1.0");
+ PackageIsRestored (package);
+ CreateAction ();
+
+ action.Execute ();
+
+ Assert.IsFalse (packageManagerFactory.FakePackageManager.IsPackageInstalled);
+ }
+
+ [Test]
+ public void Execute_ProjectHasOnePackageWhichIsRestored_AllPackagesAlreadyRestoredMessageIsLogged ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.2.3.4");
+ FakePackage package = AddPackageToPriorityRepository ("MyPackage", "1.2.3.4");
+ PackageIsRestored (package);
+ CreateAction ();
+ CaptureMessagesLogged ();
+
+ action.Execute ();
+
+ AssertMessageLogged ("All packages are already restored.");
+ AssertMessageLogged ("Skipping 'MyPackage 1.2.3.4' because it is already restored.");
+ }
+
+ [Test]
+ public void Execute_ProjectHasOnePackageWhichIsNotRestored_AllPackagesAreAlreadyRestoredMessageIsNotLogged ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.0");
+ AddPackageToPriorityRepository ("MyPackage", "1.0");
+ CreateAction ();
+ CaptureMessagesLogged ();
+
+ action.Execute ();
+
+ AssertMessageIsNotLogged ("All packages are already restored.");
+ AssertMessageLogged ("1 package restored successfully.");
+ }
+
+ [Test]
+ public void Execute_ProjectHasTwoMissingPackages_PackagesRestoredSuccessfullyMessageIsLogged ()
+ {
+ FakePackageManagementProject project = CreateSolutionWithOneProject ();
+ project.AddPackageReference ("MyPackage", "1.0");
+ project.AddPackageReference ("MyOtherPackage", "1.2");
+ AddPackageToPriorityRepository ("MyPackage", "1.0");
+ AddPackageToPriorityRepository ("MyOtherPackage", "1.2");
+ CreateAction ();
+ CaptureMessagesLogged ();
+
+ action.Execute ();
+
+ AssertMessageIsNotLogged ("All packages are already restored.");
+ AssertMessageLogged ("2 packages restored successfully.");
+ }
+
+ [Test]
+ public void Execute_TwoProjectsEachWithSameMissingPackage_PackageIsRestoredOnce ()
+ {
+ CreateSolution ();
+ FakePackageManagementProject project1 = solution.AddFakeProject ("MyProject1");
+ FakePackageManagementProject project2 = solution.AddFakeProject ("MyProject2");
+ project1.AddPackageReference ("MyPackage", "1.2.3.4");
+ project2.AddPackageReference ("MyPackage", "1.2.3.4");
+ AddPackageToPriorityRepository ("MyPackage", "1.2.3.4");
+ CreateAction ();
+ CaptureMessagesLogged ();
+
+ action.Execute ();
+
+ Assert.AreEqual (1, packageManagerFactory.FakePackageManager.PackagesInstalled.Count);
+ Assert.AreEqual ("MyPackage", packageManagerFactory.FakePackageManager.PackagePassedToInstallPackage.Id);
+ Assert.AreEqual ("1.2.3.4", packageManagerFactory.FakePackageManager.PackagePassedToInstallPackage.Version.ToString ());
+ AssertMessageLogged ("1 package restored successfully.");
+ }
+
+ [Test]
+ public void Execute_ProjectHasOneUnrestoredSolutionLevelPackage_PackageIsInstalled ()
+ {
+ CreateSolutionWithOneProject ();
+ solution.AddPackageReference ("MyPackage", "1.0");
+ FakePackage package = AddPackageToPriorityRepository ("MyPackage", "1.0");
+ CreateAction ();
+
+ action.Execute ();
+
+ Assert.AreEqual (package, packageManagerFactory.FakePackageManager.PackagePassedToInstallPackage);
+ Assert.IsTrue (packageManagerFactory.FakePackageManager.IgnoreWalkInfoPassedToInstallPackage);
+ Assert.IsTrue (packageManagerFactory.FakePackageManager.IgnoreDependenciesPassedToInstallPackage);
+ Assert.IsTrue (packageManagerFactory.FakePackageManager.AllowPrereleaseVersionsPassedToInstallPackage);
+ }
+
+ [Test]
+ public void Execute_SolutionHasTwoProjectsWithMissingPackagesButOneProjectAddedToActionForRestore_OnlyOneProjectIsRestored ()
+ {
+ CreateSolution ();
+ FakePackageManagementProject project1 = solution.AddFakeProject ("MyProject1");
+ FakePackageManagementProject project2 = solution.AddFakeProject ("MyProject2");
+ project1.AddPackageReference ("MyPackage1", "1.2.3.4");
+ project2.AddPackageReference ("MyPackage2", "1.2.3.4");
+ AddPackageToPriorityRepository ("MyPackage1", "1.2.3.4");
+ AddPackageToPriorityRepository ("MyPackage2", "1.2.3.4");
+ CreateAction ();
+ var dotNetProject = new FakeDotNetProject ();
+ dotNetProject.Name = "MyProject1";
+ solution.FakeProjectsToReturnFromGetProject.Add ("MyProject1", project1);
+ action.Project = dotNetProject;
+
+ action.Execute ();
+
+ Assert.AreEqual (1, packageManagerFactory.FakePackageManager.PackagesInstalled.Count);
+ Assert.AreEqual ("MyPackage1", packageManagerFactory.FakePackageManager.PackagePassedToInstallPackage.Id);
+ }
+
+ [Test]
+ public void Execute_OneUnrestoredSolutionLevelPackageButOneProjectAddedToActionForRestore_SolutionLevelPackageIsNotRestored ()
+ {
+ CreateSolutionWithOneProject ();
+ solution.AddPackageReference ("MyPackage", "1.0");
+ FakePackage package = AddPackageToPriorityRepository ("MyPackage", "1.0");
+ FakePackageManagementProject project1 = solution.AddFakeProject ("MyProject1");
+ FakePackageManagementProject project2 = solution.AddFakeProject ("MyProject2");
+ project1.AddPackageReference ("MyPackage1", "1.2.3.4");
+ project2.AddPackageReference ("MyPackage2", "1.2.3.4");
+ AddPackageToPriorityRepository ("MyPackage1", "1.2.3.4");
+ AddPackageToPriorityRepository ("MyPackage2", "1.2.3.4");
+ CreateAction ();
+ var dotNetProject = new FakeDotNetProject ();
+ dotNetProject.Name = "MyProject1";
+ solution.FakeProjectsToReturnFromGetProject.Add ("MyProject1", project1);
+ action.Project = dotNetProject;
+
+ action.Execute ();
+
+ Assert.AreEqual (1, packageManagerFactory.FakePackageManager.PackagesInstalled.Count);
+ Assert.AreEqual ("MyPackage1", packageManagerFactory.FakePackageManager.PackagePassedToInstallPackage.Id);
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SettingProviderTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SettingProviderTests.cs index 9661a2650f..6ce4d4f783 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SettingProviderTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SettingProviderTests.cs @@ -98,5 +98,19 @@ namespace MonoDevelop.PackageManagement.Tests Assert.AreEqual (@"d:\projects\MyProject\.nuget".ToNativePath (), fileSystemUsedToLoadSettings.Root);
Assert.AreEqual (fakeSettings, settings);
}
+
+ [Test]
+ public void LoadSettings_NuGetSettingsThrowsUnauthorizedAccessException_ExceptionHandledAndSettingsNullObjectReturned ()
+ {
+ fileSystemUsedToLoadSettings = new FakeFileSystem ();
+ configFileUsedToLoadSettings = "configFile";
+ SettingsProvider.LoadDefaultSettings = (fileSystem, configFile, machineSettings) => {
+ throw new UnauthorizedAccessException ();
+ };
+
+ ISettings settings = settingsProvider.LoadSettings ();
+
+ Assert.IsInstanceOf<NullSettings> (settings);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SolutionPackageRepositoryTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SolutionPackageRepositoryTests.cs index 6e0d17e198..7980a7767a 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SolutionPackageRepositoryTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/SolutionPackageRepositoryTests.cs @@ -38,7 +38,7 @@ namespace MonoDevelop.PackageManagement.Tests [TestFixture]
public class SolutionPackageRepositoryTests
{
- SolutionPackageRepository repository;
+ TestableSolutionPackageRepository repository;
TestablePackageManagementOptions options;
FakeSolution solution;
FakePackageRepositoryFactory fakeRepositoryFactory;
@@ -63,7 +63,7 @@ namespace MonoDevelop.PackageManagement.Tests void CreateRepository (ISolution solution, TestablePackageManagementOptions options)
{
CreateFakeRepositoryFactory ();
- repository = new SolutionPackageRepository (solution, fakeRepositoryFactory, options);
+ repository = new TestableSolutionPackageRepository (solution, fakeRepositoryFactory, options);
}
void CreateRepository (ISolution solution)
@@ -90,6 +90,30 @@ namespace MonoDevelop.PackageManagement.Tests return sharedRepository.AddFakePackageWithVersion (packageId, version);
}
+ PackageReference CreatePackageReference (string packageId, string packageVersion)
+ {
+ SemanticVersion version = null;
+ if (packageVersion != null) {
+ version = new SemanticVersion (packageVersion);
+ }
+
+ return new PackageReference (
+ packageId,
+ version,
+ null,
+ null,
+ false,
+ false
+ );
+ }
+
+ void AddFileToLocalRepositoryLookupPath (PackageReference packageReference, string filePath)
+ {
+ filePath = filePath.ToNativePath ();
+ var packageName = new PackageName (packageReference.Id, packageReference.Version);
+ repository.LocalPackageRepository.AddPackageLookupPath (packageName, filePath);
+ }
+
[Test]
public void GetInstallPath_GetInstallPathForPackage_ReturnsPackagePathInsideSolutionPackagesRepository ()
{
@@ -243,5 +267,44 @@ namespace MonoDevelop.PackageManagement.Tests PackageCollectionAssert.AreEqual (expectedPackages, packages);
}
+
+ [Test]
+ public void IsRestored_PackageReferenceHasNullVersion_ReturnsFalse ()
+ {
+ CreateSolution (@"d:\projects\myproject\myproject.sln");
+ CreateRepository (solution);
+ PackageReference packageReference = CreatePackageReference ("MyPackage", null);
+
+ bool restored = repository.IsRestored (packageReference);
+
+ Assert.IsFalse (restored);
+ }
+
+ [Test]
+ public void IsRestored_OnePackageLookupPathForPackageReference_ReturnTrue ()
+ {
+ CreateSolution (@"d:\projects\myproject\myproject.sln");
+ CreateRepository (solution);
+ PackageReference packageReference = CreatePackageReference ("MyPackage", "1.2.3.4");
+ AddFileToLocalRepositoryLookupPath (
+ packageReference,
+ @"d:\projects\myproject\packages\MyPackage.1.2.3.4\MyPackage.1.2.3.4.nupkg");
+
+ bool restored = repository.IsRestored (packageReference);
+
+ Assert.IsTrue (restored);
+ }
+
+ [Test]
+ public void IsRestored_NoPackageLookupPathsForPackageReference_ReturnFalse ()
+ {
+ CreateSolution (@"d:\projects\myproject\myproject.sln");
+ CreateRepository (solution);
+ PackageReference packageReference = CreatePackageReference ("MyPackage", "1.2.3.4");
+
+ bool restored = repository.IsRestored (packageReference);
+
+ Assert.IsFalse (restored);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatePackageActionTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatePackageActionTests.cs index b1da8e5976..7fb925db3d 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatePackageActionTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatePackageActionTests.cs @@ -40,12 +40,14 @@ namespace MonoDevelop.PackageManagement.Tests PackageManagementEvents packageManagementEvents;
FakePackageManagementProject fakeProject;
UpdatePackageHelper updatePackageHelper;
+ FakeFileRemover fileRemover;
void CreateSolution ()
{
packageManagementEvents = new PackageManagementEvents ();
fakeProject = new FakePackageManagementProject ();
- action = new UpdatePackageAction (fakeProject, packageManagementEvents);
+ fileRemover = new FakeFileRemover ();
+ action = new UpdatePackageAction (fakeProject, packageManagementEvents, fileRemover);
updatePackageHelper = new UpdatePackageHelper (action);
}
@@ -366,6 +368,61 @@ namespace MonoDevelop.PackageManagement.Tests Assert.AreEqual (expectedPackage, actualPackage);
}
+
+ [Test]
+ public void Execute_PackagesConfigFileDeletedDuringUpdate_FileServicePackagesConfigFileDeletionIsCancelled ()
+ {
+ CreateSolution ();
+ action.Package = new FakePackage ("Test");
+ string expectedFileName = @"d:\projects\MyProject\packages.config".ToNativePath ();
+ bool? fileRemovedResult = null;
+ fakeProject.UpdatePackageAction = (p, a) => {
+ fileRemovedResult = packageManagementEvents.OnFileRemoving (expectedFileName);
+ };
+ action.Execute ();
+
+ Assert.AreEqual (expectedFileName, fileRemover.FileRemoved);
+ Assert.IsFalse (fileRemovedResult.Value);
+ }
+
+ [Test]
+ public void Execute_ScriptFileDeletedDuringUpdate_FileDeletionIsNotCancelled ()
+ {
+ CreateSolution ();
+ action.Package = new FakePackage ("Test");
+ string fileName = @"d:\projects\MyProject\scripts\myscript.js".ToNativePath ();
+ bool? fileRemovedResult = null;
+ fakeProject.UpdatePackageAction = (p, a) => {
+ fileRemovedResult = packageManagementEvents.OnFileRemoving (fileName);
+ };
+ action.Execute ();
+
+ Assert.IsTrue (fileRemovedResult.Value);
+ Assert.IsNull (fileRemover.FileRemoved);
+ }
+
+ [Test]
+ public void Execute_PackageHasConstraint_LatestPackageIsNotUpdatedButPackageWithHighestVersionThatMatchesConstraint ()
+ {
+ CreateSolution ();
+ var constraintProvider = new DefaultConstraintProvider ();
+ var versionSpec = new VersionSpec ();
+ versionSpec.MinVersion = new SemanticVersion ("1.0");
+ versionSpec.IsMinInclusive = true;
+ versionSpec.IsMaxInclusive = true;
+ versionSpec.MaxVersion = new SemanticVersion ("2.0");
+ constraintProvider.AddConstraint ("MyPackage", versionSpec);
+ fakeProject.ConstraintProvider = constraintProvider;
+ fakeProject.AddFakePackageToSourceRepository ("MyPackage", "1.0");
+ FakePackage packageVersion2 = fakeProject.AddFakePackageToSourceRepository ("MyPackage", "2.0");
+ fakeProject.AddFakePackageToSourceRepository ("MyPackage", "3.0");
+ fakeProject.FakePackages.Add (new FakePackage ("MyPackage", "1.0"));
+ action.PackageId = "MyPackage";
+
+ action.Execute ();
+
+ Assert.AreEqual (packageVersion2, fakeProject.PackagePassedToUpdatePackage);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesInSolutionTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesInSolutionTests.cs index 5399737b3b..b105a94a50 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesInSolutionTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesInSolutionTests.cs @@ -97,10 +97,10 @@ namespace MonoDevelop.PackageManagement.Tests CreateUpdatedPackagesInSolution ();
FakePackageManagementProject project = AddProjectToSolution ();
project.AddPackageReference ("MyPackage", "1.0");
- FakePackage updatedPackage = AddUpdatedPackageToAggregateSourceRepository ("MyPackage", "1.1");
+ AddUpdatedPackageToAggregateSourceRepository ("MyPackage", "1.1");
updatedPackagesInSolution.CheckForUpdates ();
- UpdatedPackagesInProject updatedPackages = updatedPackagesInSolution.GetUpdatedPackages (project.Project);
+ updatedPackagesInSolution.GetUpdatedPackages (project.Project);
Assert.AreEqual (registeredPackageRepositories.FakeAggregateRepository, solution.SourceRepositoryPassedToGetProjects);
}
@@ -144,7 +144,7 @@ namespace MonoDevelop.PackageManagement.Tests CreateUpdatedPackagesInSolution ();
FakePackageManagementProject project = AddProjectToSolution ();
project.AddPackageReference ("MyPackage", "1.0");
- FakePackage updatedPackage = AddUpdatedPackageToAggregateSourceRepository ("MyPackage", "1.1");
+ AddUpdatedPackageToAggregateSourceRepository ("MyPackage", "1.1");
bool fired = false;
packageManagementEvents.UpdatedPackagesAvailable += (sender, e) => {
fired = true;
@@ -285,7 +285,7 @@ namespace MonoDevelop.PackageManagement.Tests FakePackageManagementProject project = AddProjectToSolution ();
project.AddPackageReference ("MyPackage", "1.0");
var package = FakePackage.CreatePackageWithVersion ("MyPackage", "1.0");
- FakePackage updatedPackage = AddUpdatedPackageToAggregateSourceRepository ("MyPackage", "1.1");
+ AddUpdatedPackageToAggregateSourceRepository ("MyPackage", "1.1");
updatedPackagesInSolution.CheckForUpdates ();
packageManagementEvents.OnParentPackageUninstalled (package, project);
@@ -293,6 +293,19 @@ namespace MonoDevelop.PackageManagement.Tests Assert.AreEqual (0, updatedPackages.GetPackages ().Count ());
}
+
+ [Test]
+ public void CheckForUpdates_NoPackagesUpdated_LoggerConfiguredForProject ()
+ {
+ CreateUpdatedPackagesInSolution ();
+ FakePackageManagementProject project = AddProjectToSolution ();
+ project.AddPackageReference ("MyPackage", "1.0");
+
+ updatedPackagesInSolution.CheckForUpdates ();
+ UpdatedPackagesInProject updatedPackages = updatedPackagesInSolution.GetUpdatedPackages (project.Project);
+
+ Assert.IsInstanceOf<PackageManagementLogger> (project.Logger);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesTests.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesTests.cs index 245c075cbc..31407117ee 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesTests.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.Tests/MonoDevelop.PackageManagement.Tests/UpdatedPackagesTests.cs @@ -40,7 +40,6 @@ namespace MonoDevelop.PackageManagement.Tests {
UpdatedPackages updatedPackages;
FakeServiceBasedRepository sourceRepository;
- List<FakePackage> installedPackages;
List<FakePackage> sourceRepositoryPackages;
List<IPackageName> packageNamesUsedWhenCheckingForUpdates;
bool includePreleaseUsedWhenCheckingForUpdates;
@@ -50,7 +49,6 @@ namespace MonoDevelop.PackageManagement.Tests public void Init ()
{
sourceRepository = new FakeServiceBasedRepository ();
- installedPackages = new List<FakePackage> ();
sourceRepositoryPackages = new List<FakePackage> ();
packageNamesUsedWhenCheckingForUpdates = new List<IPackageName> ();
project = new FakePackageManagementProject ();
@@ -63,7 +61,12 @@ namespace MonoDevelop.PackageManagement.Tests packageNamesUsedWhenCheckingForUpdates.AddRange (packagesNames.Select (p => (IPackageName)p));
return sourceRepositoryPackages.AsQueryable ();
};
- updatedPackages = new UpdatedPackages (project, sourceRepository);
+ CreateUpdatedPackages (sourceRepository);
+ }
+
+ void CreateUpdatedPackages (IPackageRepository repository)
+ {
+ updatedPackages = new UpdatedPackages (project, repository);
}
FakePackage AddPackageToSourceRepository (string id, string version)
@@ -106,7 +109,7 @@ namespace MonoDevelop.PackageManagement.Tests AddPackageToSourceRepository ("Test", "1.1");
CreateUpdatedPackages ();
- IEnumerable<IPackage> packages = updatedPackages.GetUpdatedPackages ();
+ updatedPackages.GetUpdatedPackages ();
IPackageName packageChecked = packageNamesUsedWhenCheckingForUpdates.FirstOrDefault ();
Assert.AreSame ("Test", packageChecked.Id);
@@ -167,5 +170,31 @@ namespace MonoDevelop.PackageManagement.Tests Assert.IsFalse (includePreleaseUsedWhenCheckingForUpdates);
}
+
+ [Test]
+ public void GetUpdatedPackages_OnePackageReferencedWithConstraintAndUpdatesAvailable_LatestVersionReturnedBasedOnConstraint ()
+ {
+ AddPackageReference ("Test", "1.0");
+ FakePackage package = AddPackageToSourceRepository ("Test", "2.0");
+ FakePackage [] expectedPackages = new [] {
+ package
+ };
+ AddPackageToSourceRepository ("Test", "3.0");
+ var versionSpec = new VersionSpec ();
+ versionSpec.MinVersion = new SemanticVersion ("1.0");
+ versionSpec.IsMinInclusive = true;
+ versionSpec.MaxVersion = new SemanticVersion ("2.0");
+ versionSpec.IsMaxInclusive = true;
+ var constraintProvider = new DefaultConstraintProvider ();
+ constraintProvider.AddConstraint ("Test", versionSpec);
+ project.ConstraintProvider = constraintProvider;
+ var repository = new FakePackageRepository ();
+ repository.FakePackages = sourceRepositoryPackages;
+ CreateUpdatedPackages (repository);
+
+ IEnumerable<IPackage> packages = updatedPackages.GetUpdatedPackages ();
+
+ PackageCollectionAssert.AreEqual (expectedPackages, packages);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.addin.xml b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.addin.xml index 22c0ce5ad2..fd9a79ccc2 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.addin.xml +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.addin.xml @@ -4,7 +4,6 @@ <Import assembly="MonoDevelop.PackageManagement.dll" />
<Import assembly="Microsoft.Web.XmlTransform.dll" />
<Import assembly="NuGet.Core.dll" />
- <Import file="NuGet.exe" />
</Runtime>
<Extension path = "/MonoDevelop/Ide/Commands">
@@ -22,7 +21,7 @@ id="MonoDevelop.PackageManagement.Commands.Restore"
_description="Restore missing packages"
_label="_Restore"
- defaultHandler="MonoDevelop.PackageManagement.Commands.RestorePackagesHandler" />
+ defaultHandler="MonoDevelop.PackageManagement.Commands.RestorePackagesInProjectHandler" />
<Command
id="MonoDevelop.PackageManagement.Commands.PackageReferenceNodeCommands.ShowPackageVersion"
_description="Current package version"
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.csproj b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.csproj index e33649710f..55e16bc4de 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.csproj +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement.csproj @@ -131,8 +131,6 @@ <Compile Include="MonoDevelop.PackageManagement\ManagePackagesViewTitle.cs" /> <Compile Include="MonoDevelop.PackageManagement\MonoDevelopCredentialProvider.cs" /> <Compile Include="MonoDevelop.PackageManagement\MSBuildProjectExtensions.cs" /> - <Compile Include="MonoDevelop.PackageManagement\NuGetExePath.cs" /> - <Compile Include="MonoDevelop.PackageManagement\NuGetPackageRestoreCommandLine.cs" /> <Compile Include="MonoDevelop.PackageManagement\PackageActionRunner.cs" /> <Compile Include="MonoDevelop.PackageManagement\PackageFromRepository.cs" /> <Compile Include="MonoDevelop.PackageManagement\PackageLicenseViewModel.cs" /> @@ -348,6 +346,19 @@ <Compile Include="MonoDevelop.PackageManagement\UpdatePackagesProgressMonitorStatusMessage.cs" /> <Compile Include="MonoDevelop.PackageManagement\CheckForUpdatedPackagesAction.cs" /> <Compile Include="MonoDevelop.PackageManagement\RestoreBeforeUpdateAction.cs" /> + <Compile Include="MonoDevelop.PackageManagement\MonoDevelopAggregateRepository.cs" /> + <Compile Include="MonoDevelop.PackageManagement\RestorePackagesAction.cs" /> + <Compile Include="MonoDevelop.PackageManagement.Commands\RestorePackagesInProjectHandler.cs" /> + <Compile Include="MonoDevelop.PackageManagement\FailingPackageRepository.cs" /> + <Compile Include="MonoDevelop.PackageManagement\FileRemovingEventArgs.cs" /> + <Compile Include="MonoDevelop.PackageManagement\PreventPackagesConfigFileBeingRemovedOnUpdateMonitor.cs" /> + <Compile Include="MonoDevelop.PackageManagement\FilePathExtensions.cs" /> + <Compile Include="MonoDevelop.PackageManagement\FileRemover.cs" /> + <Compile Include="MonoDevelop.PackageManagement\IFileRemover.cs" /> + <Compile Include="MonoDevelop.PackageManagement\IPackageManagementProjectOperations.cs" /> + <Compile Include="MonoDevelop.PackageManagement\PackageManagementPackageReference.cs" /> + <Compile Include="MonoDevelop.PackageManagement\PackageManagementProjectOperations.cs" /> + <Compile Include="MonoDevelop.PackageManagement\PackageManagementPackageReferenceEventArgs.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="MonoDevelop.PackageManagement.addin.xml" /> @@ -424,10 +435,6 @@ <Folder Include="MonoDevelop.PackageManagement.NodeBuilders\" /> </ItemGroup> <ItemGroup> - <None Include="..\..\..\external\nuget-binary\NuGet.exe"> - <Link>NuGet.exe</Link> - <CopyToOutputDirectory>Always</CopyToOutputDirectory> - </None> <None Include="..\..\..\external\nuget-binary\NuGet-LICENSE.txt"> <Link>NuGet-LICENSE.txt</Link> <CopyToOutputDirectory>Always</CopyToOutputDirectory> diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AggregateExceptionErrorMessage.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AggregateExceptionErrorMessage.cs index 35248deea3..c8e33a8997 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AggregateExceptionErrorMessage.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AggregateExceptionErrorMessage.cs @@ -36,15 +36,23 @@ namespace ICSharpCode.PackageManagement {
AggregateException ex;
StringBuilder errorMessage = new StringBuilder();
-
+
public AggregateExceptionErrorMessage(AggregateException ex)
+ : this (null, ex)
+ {
+ }
+
+ public AggregateExceptionErrorMessage (string message, AggregateException ex)
{
this.ex = ex;
- BuildErrorMessage();
+ BuildErrorMessage (message);
}
- void BuildErrorMessage()
+ void BuildErrorMessage (string message)
{
+ if (!String.IsNullOrEmpty (message)) {
+ errorMessage.AppendLine (message);
+ }
BuildErrorMessage(ex.InnerExceptions);
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AvailablePackagesViewModel.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AvailablePackagesViewModel.cs index bfe93e3fbf..555e55f567 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AvailablePackagesViewModel.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/AvailablePackagesViewModel.cs @@ -32,22 +32,26 @@ using System.Linq; using MonoDevelop.PackageManagement;
using NuGet;
+using MonoDevelop.Core;
namespace ICSharpCode.PackageManagement
{
public class AvailablePackagesViewModel : PackagesViewModel
{
+ ISolutionPackageRepository solutionPackageRepository;
IPackageRepository repository;
string errorMessage;
IRecentPackageRepository recentPackageRepository;
- public AvailablePackagesViewModel(
+ public AvailablePackagesViewModel (
+ IPackageManagementSolution solution,
IRegisteredPackageRepositories registeredPackageRepositories,
IRecentPackageRepository recentPackageRepository,
IPackageViewModelFactory packageViewModelFactory,
ITaskFactory taskFactory)
: base(registeredPackageRepositories, packageViewModelFactory, taskFactory)
{
+ this.solutionPackageRepository = solution.GetRepository ();
this.recentPackageRepository = recentPackageRepository;
IsSearchable = true;
@@ -120,36 +124,93 @@ namespace ICSharpCode.PackageManagement .DistinctLast<IPackage>(PackageEqualityComparer.Id);
}
+ /// <summary>
+ /// Package prioritization:
+ ///
+ /// Recent packages first.
+ /// Packages in solution.
+ /// Packages from active package source.
+ /// </summary>
protected override IEnumerable<IPackage> PrioritizePackages (IEnumerable<IPackage> packages, PackageSearchCriteria search)
{
- List<IPackage> recentPackages = GetRecentPackages (search).ToList ();
+ List<IPackage> prioritizedPackages = GetPrioritizedPackages (search).ToList ();
- if (PackageViewModels.Count == 0) {
- foreach (IPackage package in recentPackages) {
- yield return package;
- }
+ foreach (IPackage package in prioritizedPackages) {
+ yield return package;
}
foreach (IPackage package in packages) {
- if (!recentPackages.Contains (package, PackageEqualityComparer.IdAndVersion)) {
+ if (!prioritizedPackages.Contains (package, PackageEqualityComparer.IdAndVersion)) {
yield return package;
}
}
}
- IEnumerable<IPackage> GetRecentPackages (PackageSearchCriteria search)
+ IEnumerable<IPackage> GetPrioritizedPackages (PackageSearchCriteria search)
{
if (search.IsPackageVersionSearch) {
- return Enumerable.Empty<IPackage> ();
+ yield break;
+ }
+
+ List<IPackage> prioritizedPackages = GetRecentPackages (search).ToList ();
+
+ if (PackageViewModels.Count == 0) {
+ foreach (IPackage package in prioritizedPackages) {
+ yield return package;
+ }
+
+ foreach (IPackage package in GetSolutionPackages (search)) {
+ if (!prioritizedPackages.Contains (package, PackageEqualityComparer.IdAndVersion)) {
+ prioritizedPackages.Add (package);
+ yield return package;
+ }
+ }
}
+ }
+
+ IEnumerable<IPackage> GetRecentPackages (PackageSearchCriteria search)
+ {
return recentPackageRepository.Search (search.SearchText, IncludePrerelease);
}
+ IEnumerable<IPackage> GetSolutionPackages (PackageSearchCriteria search)
+ {
+ return solutionPackageRepository
+ .GetPackages ()
+ .Find (search.SearchText)
+ .FilterByPrerelease (IncludePrerelease);
+ }
+
protected override PackageViewModel CreatePackageViewModel (IPackage package, PackageSearchCriteria search)
{
PackageViewModel viewModel = base.CreatePackageViewModel (package, search);
viewModel.ShowVersionInsteadOfDownloadCount = search.IsPackageVersionSearch;
return viewModel;
}
+
+ protected override string GetWarningMessage ()
+ {
+ var aggregateRepository = repository as MonoDevelopAggregateRepository;
+ if (aggregateRepository != null) {
+ if (aggregateRepository.AllFailed ()) {
+ return GetAllPackageSourcesCouldNotBeReachedErrorMessage (aggregateRepository);
+ } else if (aggregateRepository.AnyFailures ()) {
+ return GetSomePackageSourcesCouldNotBeReachedErrorMessage (aggregateRepository);
+ }
+ }
+ return String.Empty;
+ }
+
+ string GetAllPackageSourcesCouldNotBeReachedErrorMessage (MonoDevelopAggregateRepository repository)
+ {
+ string message = GettextCatalog.GetString ("All package sources could not be reached.");
+ return new AggregateExceptionErrorMessage (message, repository.GetAggregateException ()).ToString ();
+ }
+
+ string GetSomePackageSourcesCouldNotBeReachedErrorMessage (MonoDevelopAggregateRepository repository)
+ {
+ string message = GettextCatalog.GetString ("Some package sources could not be reached.");
+ return new AggregateExceptionErrorMessage (message, repository.GetAggregateException ()).ToString ();
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/BackgroundPackageActionRunner.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/BackgroundPackageActionRunner.cs index d02f01385f..9ba0d464d1 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/BackgroundPackageActionRunner.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/BackgroundPackageActionRunner.cs @@ -80,9 +80,16 @@ namespace MonoDevelop.PackageManagement }
}
+ public void RunAndWait (ProgressMonitorStatusMessage progressMessage, IEnumerable<IPackageAction> actions)
+ {
+ AddInstallActionsToPendingQueue (actions);
+ packageManagementEvents.OnPackageOperationsStarting ();
+ DispatchService.BackgroundDispatchAndWait (() => RunActionsWithProgressMonitor (progressMessage, actions.ToList ()));
+ }
+
void RunActionsWithProgressMonitor (ProgressMonitorStatusMessage progressMessage, IList<IPackageAction> installPackageActions)
{
- using (IProgressMonitor monitor = progressMonitorFactory.CreateProgressMonitor (progressMessage.Status)) {
+ using (ProgressMonitor monitor = progressMonitorFactory.CreateProgressMonitor (progressMessage.Status)) {
using (PackageManagementEventsMonitor eventMonitor = CreateEventMonitor (monitor)) {
try {
monitor.BeginTask (null, installPackageActions.Count);
@@ -102,20 +109,20 @@ namespace MonoDevelop.PackageManagement }
}
- PackageManagementEventsMonitor CreateEventMonitor (IProgressMonitor monitor)
+ PackageManagementEventsMonitor CreateEventMonitor (ProgressMonitor monitor)
{
return CreateEventMonitor (monitor, packageManagementEvents, progressProvider);
}
protected virtual PackageManagementEventsMonitor CreateEventMonitor (
- IProgressMonitor monitor,
+ ProgressMonitor monitor,
IPackageManagementEvents packageManagementEvents,
IProgressProvider progressProvider)
{
return new PackageManagementEventsMonitor (monitor, packageManagementEvents, progressProvider);
}
- void RunActionsWithProgressMonitor (IProgressMonitor monitor, IList<IPackageAction> packageActions)
+ void RunActionsWithProgressMonitor (ProgressMonitor monitor, IList<IPackageAction> packageActions)
{
foreach (IPackageAction action in packageActions) {
action.Execute ();
@@ -138,7 +145,7 @@ namespace MonoDevelop.PackageManagement public void ShowError (ProgressMonitorStatusMessage progressMessage, string error)
{
- using (IProgressMonitor monitor = progressMonitorFactory.CreateProgressMonitor (progressMessage.Status)) {
+ using (ProgressMonitor monitor = progressMonitorFactory.CreateProgressMonitor (progressMessage.Status)) {
monitor.Log.WriteLine (error);
monitor.ReportError (progressMessage.Error, null);
monitor.ShowPackageConsole ();
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/DotNetProjectExtensions.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/DotNetProjectExtensions.cs index 3d38c585c2..9d771745d9 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/DotNetProjectExtensions.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/DotNetProjectExtensions.cs @@ -33,6 +33,7 @@ using MonoDevelop.PackageManagement; using MonoDevelop.Projects;
using MonoDevelop.Projects.Formats.MSBuild;
using NuGet;
+using System.Linq;
namespace ICSharpCode.PackageManagement
{
@@ -43,23 +44,7 @@ namespace ICSharpCode.PackageManagement public static bool IsWebProject(this IDotNetProject project)
{
- return project.HasProjectType(WebApplication) || project.HasProjectType(WebSite);
- }
-
- public static bool HasProjectType(this IDotNetProject project, Guid projectTypeGuid)
- {
- foreach (string guid in project.GetProjectTypeGuids()) {
- if (IsMatch(projectTypeGuid, guid)) {
- return true;
- }
- }
- return false;
- }
-
- public static string[] GetProjectTypeGuids(this IDotNetProject project)
- {
- string projectTypeGuids = project.GetProjectTypeGuidPropertyValue();
- return projectTypeGuids.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
+ return project.FlavorGuids.Any (id => IsMatch (WebApplication, id) || IsMatch (WebSite, id));
}
static bool IsMatch(Guid guid, string guidStringToMatch)
@@ -71,15 +56,6 @@ namespace ICSharpCode.PackageManagement return false;
}
- public static string GetProjectTypeGuidPropertyValue (this IDotNetProject project)
- {
- string propertyValue = null;
- if (project.ExtendedProperties.Contains("ProjectTypeGuids")) {
- propertyValue = project.ExtendedProperties["ProjectTypeGuids"] as String;
- }
- return propertyValue ?? String.Empty;
- }
-
public static bool HasPackages (this DotNetProject project)
{
return File.Exists (project.GetPackagesConfigFilePath ());
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FailingPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FailingPackageRepository.cs new file mode 100644 index 0000000000..e45a612994 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FailingPackageRepository.cs @@ -0,0 +1,76 @@ +//
+// FailingPackageRepository.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement
+{
+ /// <summary>
+ /// Wraps access to a package repository that could not be created due to an invalid
+ /// Url. A call to any method will return the original exception that was thrown.
+ /// This is only used when creating an AggregateRepository so it does not prevent packages
+ /// being returned from other valid package repositories.
+ /// </summary>
+ public class FailingPackageRepository : IPackageRepository
+ {
+ string source;
+ Exception exception;
+
+ public FailingPackageRepository (string source, Exception exception)
+ {
+ this.source = source;
+ this.exception = exception;
+ }
+
+ public IQueryable<IPackage> GetPackages ()
+ {
+ throw exception;
+ }
+
+ public void AddPackage (IPackage package)
+ {
+ throw exception;
+ }
+
+ public void RemovePackage (IPackage package)
+ {
+ throw exception;
+ }
+
+ public string Source {
+ get { return source; }
+ }
+
+ public PackageSaveModes PackageSaveMode { get; set; }
+
+ public bool SupportsPrereleasePackages {
+ get { return true; }
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FilePathExtensions.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FilePathExtensions.cs new file mode 100644 index 0000000000..38faa5f7de --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FilePathExtensions.cs @@ -0,0 +1,45 @@ +//
+// FilePathExtensions.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using MonoDevelop.Core;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement
+{
+ public static class FilePathExtensions
+ {
+ public static bool IsPackagesConfigFileName (this FilePath filePath)
+ {
+ if (filePath == null) {
+ return false;
+ }
+
+ return Constants.PackageReferenceFile.Equals (filePath.FileName, StringComparison.OrdinalIgnoreCase);
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FileRemover.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FileRemover.cs new file mode 100644 index 0000000000..96849ca9d0 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FileRemover.cs @@ -0,0 +1,40 @@ +//
+// FileRemover.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.IO;
+
+namespace MonoDevelop.PackageManagement
+{
+ public class FileRemover : IFileRemover
+ {
+ public void RemoveFile (string fileName)
+ {
+ File.Delete (fileName);
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FileRemovingEventArgs.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FileRemovingEventArgs.cs new file mode 100644 index 0000000000..557b185dca --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/FileRemovingEventArgs.cs @@ -0,0 +1,47 @@ +//
+// FileRemovingEventArgs.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using MonoDevelop.Core;
+
+namespace MonoDevelop.PackageManagement
+{
+ public class FileRemovingEventArgs : EventArgs
+ {
+ public FileRemovingEventArgs (string fileName)
+ {
+ FileName = new FilePath (fileName);
+ }
+
+ public FilePath FileName { get; private set; }
+
+ /// <summary>
+ /// Stops the file from being removed.
+ /// </summary>
+ public bool IsCancelled { get; set; }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IFileRemover.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IFileRemover.cs new file mode 100644 index 0000000000..b9a19bb0d4 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IFileRemover.cs @@ -0,0 +1,36 @@ +//
+// IFileRemover.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace MonoDevelop.PackageManagement
+{
+ public interface IFileRemover
+ {
+ void RemoveFile (string fileName);
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageFromRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageFromRepository.cs index 4e3b61a589..947bed8b9f 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageFromRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageFromRepository.cs @@ -37,5 +37,6 @@ namespace ICSharpCode.PackageManagement bool HasDependencies { get; }
DateTime? LastUpdated { get; }
Uri GalleryUrl { get; }
+ bool IsValid { get; }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementEvents.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementEvents.cs index 53abfe8c8b..0e476e576f 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementEvents.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementEvents.cs @@ -29,6 +29,7 @@ using System;
using System.Collections.Generic;
using MonoDevelop.Core;
+using MonoDevelop.PackageManagement;
using NuGet;
namespace ICSharpCode.PackageManagement
@@ -47,6 +48,7 @@ namespace ICSharpCode.PackageManagement event EventHandler<PackageOperationMessageLoggedEventArgs> PackageOperationMessageLogged;
event EventHandler PackagesRestored;
event EventHandler<FileEventArgs> FileChanged;
+ event EventHandler<FileRemovingEventArgs> FileRemoving;
event EventHandler UpdatedPackagesAvailable;
void OnPackageOperationsStarting();
@@ -62,5 +64,6 @@ namespace ICSharpCode.PackageManagement void OnPackagesRestored();
void OnFileChanged(string path);
void OnUpdatedPackagesAvailable ();
+ bool OnFileRemoving (string path);
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProgressMonitorFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProgressMonitorFactory.cs index efecca66e2..ff0d07af86 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProgressMonitorFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProgressMonitorFactory.cs @@ -31,7 +31,7 @@ namespace MonoDevelop.PackageManagement {
public interface IPackageManagementProgressMonitorFactory
{
- IProgressMonitor CreateProgressMonitor (string statusText);
+ ProgressMonitor CreateProgressMonitor (string statusText);
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProject.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProject.cs index 1e0d1c1a9a..5c325681e4 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProject.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProject.cs @@ -52,6 +52,8 @@ namespace ICSharpCode.PackageManagement DotNetProject DotNetProject { get; }
IDotNetProject Project { get; }
+ IPackageConstraintProvider ConstraintProvider { get; }
+
bool IsPackageInstalled(IPackage package);
bool IsPackageInstalled(string packageId);
bool HasOlderPackageInstalled(IPackage package);
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProjectOperations.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProjectOperations.cs new file mode 100644 index 0000000000..f47cbe3c0b --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementProjectOperations.cs @@ -0,0 +1,48 @@ +//
+// IPackageManagementProjectOperations.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using MonoDevelop.Projects;
+using System.Collections.Generic;
+
+namespace MonoDevelop.PackageManagement
+{
+ /// <summary>
+ /// Provides a simplified interface for working with NuGet packages in a project.
+ ///
+ /// Used by the ComponentReferencingProjectAdaptor in Xamarin.Ide so keep the NuGet
+ /// package management logic in the NuGet addin.
+ /// </summary>
+ public interface IPackageManagementProjectOperations
+ {
+ void InstallPackages (string packageSourceUrl, Project project, IEnumerable<PackageManagementPackageReference> packages);
+ IEnumerable<PackageManagementPackageReference> GetInstalledPackages (Project project);
+
+ event EventHandler<PackageManagementPackageReferenceEventArgs> PackageReferenceAdded;
+ event EventHandler<PackageManagementPackageReferenceEventArgs> PackageReferenceRemoved;
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementSolution.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementSolution.cs index 03f279d604..f7c0036588 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementSolution.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagementSolution.cs @@ -53,6 +53,7 @@ namespace ICSharpCode.PackageManagement IQueryable<IPackage> GetPackages();
IEnumerable<IPackage> GetPackagesInReverseDependencyOrder();
string GetInstallPath(IPackage package);
+ ISolutionPackageRepository GetRepository ();
bool IsOpen { get; }
string FileName { get; }
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagerFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagerFactory.cs index 0428fa1a84..49b0f81ba2 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagerFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageManagerFactory.cs @@ -37,5 +37,9 @@ namespace ICSharpCode.PackageManagement ISharpDevelopPackageManager CreatePackageManager (
IPackageRepository sourceRepository,
IDotNetProject project);
+
+ IPackageManager CreatePackageManager (
+ IPackageRepository sourceRepository,
+ ISolutionPackageRepository solutionPackageRepository);
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryCache.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryCache.cs index 5384a70332..8524d1a07a 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryCache.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryCache.cs @@ -35,5 +35,6 @@ namespace ICSharpCode.PackageManagement {
IRecentPackageRepository RecentPackageRepository { get; }
IPackageRepository CreateAggregateRepository();
+ IPackageRepository CreateAggregateWithPriorityMachineCacheRepository ();
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryExtensions.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryExtensions.cs index 8a498fee44..fce99ffbc0 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryExtensions.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IPackageRepositoryExtensions.cs @@ -42,5 +42,10 @@ namespace ICSharpCode.PackageManagement {
return repository.StartOperation(RepositoryOperationNames.Update, mainPackageId, mainPackageVersion);
}
+
+ public static IDisposable StartRestoreOperation (this IPackageRepository repository, string mainPackageId = null, string mainPackageVersion = null)
+ {
+ return repository.StartOperation (RepositoryOperationNames.Restore, mainPackageId, mainPackageVersion);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IProject.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IProject.cs index d359be3c57..4455e85c76 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IProject.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/IProject.cs @@ -27,6 +27,7 @@ using System;
using System.Collections;
using MonoDevelop.Core;
+using System.Collections.Generic;
namespace MonoDevelop.PackageManagement
{
@@ -37,6 +38,7 @@ namespace MonoDevelop.PackageManagement FilePath BaseDirectory { get; }
ISolution ParentSolution { get; }
IDictionary ExtendedProperties { get; }
+ IEnumerable<string> FlavorGuids { get; }
void Save ();
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ISolutionPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ISolutionPackageRepository.cs index e73cd209f5..3c00c845e5 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ISolutionPackageRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ISolutionPackageRepository.cs @@ -41,7 +41,9 @@ namespace ICSharpCode.PackageManagement IEnumerable<IPackage> GetPackagesByReverseDependencyOrder();
IQueryable<IPackage> GetPackages();
bool IsInstalled(IPackage package);
-
+ bool IsRestored (PackageReference packageReference);
+ IEnumerable<PackageReference> GetPackageReferences ();
+
ISharedPackageRepository Repository { get; }
IFileSystem FileSystem { get; }
IPackagePathResolver PackagePathResolver { get; }
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/MonoDevelopAggregateRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/MonoDevelopAggregateRepository.cs new file mode 100644 index 0000000000..3a140e6802 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/MonoDevelopAggregateRepository.cs @@ -0,0 +1,68 @@ +//
+// MonoDevelopAggregateRepository.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Linq;
+using MonoDevelop.Core;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement
+{
+ public class MonoDevelopAggregateRepository : AggregateRepository
+ {
+ ConcurrentQueue<Exception> failures = new ConcurrentQueue<Exception> ();
+
+ public MonoDevelopAggregateRepository (IEnumerable<IPackageRepository> repositories)
+ : base (repositories)
+ {
+ }
+
+ public override void LogRepository (IPackageRepository repository, Exception ex)
+ {
+ base.LogRepository (repository, ex);
+ LoggingService.LogInfo ("PackageRepository failure.", ex);
+ failures.Enqueue (ex);
+ }
+
+ public bool AnyFailures ()
+ {
+ return failures.Count > 0;
+ }
+
+ public bool AllFailed ()
+ {
+ return failures.Count >= Repositories.Count ();
+ }
+
+ public AggregateException GetAggregateException ()
+ {
+ return new AggregateException (failures);
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/NuGetExePath.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/NuGetExePath.cs deleted file mode 100644 index e4646e019b..0000000000 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/NuGetExePath.cs +++ /dev/null @@ -1,46 +0,0 @@ -//
-// NuGetExePath.cs
-//
-// Author:
-// Matt Ward <ward.matt@gmail.com>
-//
-// Copyright (C) 2013 Matthew Ward
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-
-namespace ICSharpCode.PackageManagement
-{
- public static class NuGetExePath
- {
- public static string GetPath()
- {
- return Path.Combine(GetDirectory(), "NuGet.exe");
- }
-
- static string GetDirectory()
- {
- return Path.GetDirectoryName(typeof(NuGetExePath).Assembly.Location);
- }
- }
-}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/NuGetPackageRestoreCommandLine.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/NuGetPackageRestoreCommandLine.cs deleted file mode 100644 index 068061bbf4..0000000000 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/NuGetPackageRestoreCommandLine.cs +++ /dev/null @@ -1,108 +0,0 @@ -//
-// NuGetPackageRestoreCommandLine.cs
-//
-// Author:
-// Matt Ward <ward.matt@gmail.com>
-//
-// Copyright (C) 2013 Matthew Ward
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-
-using System;
-using System.IO;
-using MonoDevelop.Core.Assemblies;
-using NuGet;
-
-namespace ICSharpCode.PackageManagement
-{
- public class NuGetPackageRestoreCommandLine
- {
- MonoRuntimeInfo monoRuntime;
- bool isMonoRuntime;
-
- public NuGetPackageRestoreCommandLine (IPackageManagementSolution solution)
- : this (
- solution,
- MonoRuntimeInfo.FromCurrentRuntime (),
- EnvironmentUtility.IsMonoRuntime)
- {
- }
-
- public NuGetPackageRestoreCommandLine (
- IPackageManagementSolution solution,
- MonoRuntimeInfo monoRuntime,
- bool isMonoRuntime)
- {
- this.monoRuntime = monoRuntime;
- this.isMonoRuntime = isMonoRuntime;
-
- GenerateCommandLine(solution);
- GenerateWorkingDirectory(solution);
- }
-
- public string Command { get; set; }
- public string Arguments { get; private set; }
- public string WorkingDirectory { get; private set; }
-
- void GenerateCommandLine(IPackageManagementSolution solution)
- {
- if (isMonoRuntime) {
- GenerateMonoCommandLine(solution);
- } else {
- GenerateWindowsCommandLine(solution);
- }
- }
-
- void GenerateMonoCommandLine(IPackageManagementSolution solution)
- {
- Arguments = String.Format(
- "--runtime=v4.0 \"{0}\" restore -NonInteractive \"{1}\"",
- NuGetExePath.GetPath(),
- solution.FileName);
-
- Command = Path.Combine (monoRuntime.Prefix, "bin", "mono");
- }
-
- void GenerateWindowsCommandLine(IPackageManagementSolution solution)
- {
- Arguments = String.Format("restore -NonInteractive \"{0}\"", solution.FileName);
- Command = NuGetExePath.GetPath();
- }
-
- void GenerateWorkingDirectory(IPackageManagementSolution solution)
- {
- WorkingDirectory = Path.GetDirectoryName(solution.FileName);
- }
-
- public override string ToString()
- {
- return String.Format("{0} {1}", GetQuotedCommand(), Arguments);
- }
-
- string GetQuotedCommand()
- {
- if (Command.Contains(" ")) {
- return String.Format("\"{0}\"", Command);
- }
- return Command;
- }
- }
-}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityHandler.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityHandler.cs index 71ac6498f1..07d943a34b 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityHandler.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityHandler.cs @@ -32,7 +32,7 @@ namespace MonoDevelop.PackageManagement {
public class PackageCompatibilityHandler
{
- public PackageCompatibilityHandler (ProjectTargetFrameworkMonitor projectTargetFrameworkMonitor)
+ public void MonitorTargetFrameworkChanges (ProjectTargetFrameworkMonitor projectTargetFrameworkMonitor)
{
projectTargetFrameworkMonitor.ProjectTargetFrameworkChanged += ProjectTargetFrameworkChanged;
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityRunner.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityRunner.cs index 8a7092cbc3..aced2f1bd1 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityRunner.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageCompatibilityRunner.cs @@ -40,7 +40,7 @@ namespace MonoDevelop.PackageManagement IRegisteredPackageRepositories registeredRepositories;
IPackageManagementProgressMonitorFactory progressMonitorFactory;
ProgressMonitorStatusMessage progressMessage;
- IProgressMonitor progressMonitor;
+ ProgressMonitor progressMonitor;
IPackageManagementEvents packageManagementEvents;
IProgressProvider progressProvider;
@@ -101,18 +101,18 @@ namespace MonoDevelop.PackageManagement return ProgressMonitorStatusMessageFactory.CreateCheckingPackageCompatibilityMessage ();
}
- IProgressMonitor CreateProgressMonitor ()
+ ProgressMonitor CreateProgressMonitor ()
{
return progressMonitorFactory.CreateProgressMonitor (progressMessage.Status);
}
- PackageManagementEventsMonitor CreateEventMonitor (IProgressMonitor monitor)
+ PackageManagementEventsMonitor CreateEventMonitor (ProgressMonitor monitor)
{
return CreateEventMonitor (monitor, packageManagementEvents, progressProvider);
}
protected virtual PackageManagementEventsMonitor CreateEventMonitor (
- IProgressMonitor monitor,
+ ProgressMonitor monitor,
IPackageManagementEvents packageManagementEvents,
IProgressProvider progressProvider)
{
@@ -157,7 +157,7 @@ namespace MonoDevelop.PackageManagement ShowPackageConsole (progressMonitor);
}
- protected virtual void ShowPackageConsole (IProgressMonitor progressMonitor)
+ protected virtual void ShowPackageConsole (ProgressMonitor progressMonitor)
{
progressMonitor.ShowPackageConsole ();
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageFromRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageFromRepository.cs index 90ea1cb78e..56a5227376 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageFromRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageFromRepository.cs @@ -221,5 +221,15 @@ namespace ICSharpCode.PackageManagement public bool DevelopmentDependency {
get { return package.DevelopmentDependency; }
}
+
+ public bool IsValid {
+ get {
+ var zipPackage = package as OptimizedZipPackage;
+ if (zipPackage != null) {
+ return zipPackage.IsValid;
+ }
+ return true;
+ }
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEvents.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEvents.cs index 4b7f318e1d..4500ce5cd2 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEvents.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEvents.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic;
using MonoDevelop.Core;
using NuGet;
+using MonoDevelop.PackageManagement;
namespace ICSharpCode.PackageManagement
{
@@ -161,5 +162,17 @@ namespace ICSharpCode.PackageManagement UpdatedPackagesAvailable (this, new EventArgs ());
}
}
+
+ public event EventHandler<FileRemovingEventArgs> FileRemoving;
+
+ public bool OnFileRemoving (string path)
+ {
+ if (FileRemoving != null) {
+ var eventArgs = new FileRemovingEventArgs (path);
+ FileRemoving (this, eventArgs);
+ return !eventArgs.IsCancelled;
+ }
+ return true;
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEventsMonitor.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEventsMonitor.cs index 7594cb305e..b313ae98f0 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEventsMonitor.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementEventsMonitor.cs @@ -36,7 +36,7 @@ namespace MonoDevelop.PackageManagement {
public class PackageManagementEventsMonitor : IDisposable
{
- IProgressMonitor progressMonitor;
+ ProgressMonitor progressMonitor;
IPackageManagementEvents packageManagementEvents;
IProgressProvider progressProvider;
FileConflictResolution lastFileConflictResolution;
@@ -45,7 +45,7 @@ namespace MonoDevelop.PackageManagement List<FileEventArgs> fileChangedEvents = new List<FileEventArgs> ();
public PackageManagementEventsMonitor (
- IProgressMonitor progressMonitor,
+ ProgressMonitor progressMonitor,
IPackageManagementEvents packageManagementEvents,
IProgressProvider progressProvider)
{
@@ -190,7 +190,7 @@ namespace MonoDevelop.PackageManagement packageManagementEvents.OnPackageOperationError (ex);
}
- protected virtual void ShowPackageConsole (IProgressMonitor progressMonitor)
+ protected virtual void ShowPackageConsole (ProgressMonitor progressMonitor)
{
progressMonitor.ShowPackageConsole ();
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementFileService.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementFileService.cs index 4c8b99917e..990ddabfdc 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementFileService.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementFileService.cs @@ -48,7 +48,9 @@ namespace ICSharpCode.PackageManagement public void RemoveFile(string path)
{
- FileService.DeleteFile(path);
+ if (packageManagementEvents.OnFileRemoving (path)) {
+ FileService.DeleteFile (path);
+ }
}
public void RemoveDirectory(string path)
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementPackageReference.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementPackageReference.cs new file mode 100644 index 0000000000..08cd591c28 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementPackageReference.cs @@ -0,0 +1,43 @@ +//
+// PackageManagementPackageReference.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace MonoDevelop.PackageManagement
+{
+ public class PackageManagementPackageReference
+ {
+ public PackageManagementPackageReference (string id, string version)
+ {
+ Id = id;
+ Version = version;
+ }
+
+ public string Id { get; set; }
+ public string Version { get; set; }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementPackageReferenceEventArgs.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementPackageReferenceEventArgs.cs new file mode 100644 index 0000000000..16e565e8df --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementPackageReferenceEventArgs.cs @@ -0,0 +1,44 @@ +//
+// PackageManagementPackageReferenceEventArgs.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using MonoDevelop.Projects;
+
+namespace MonoDevelop.PackageManagement
+{
+ public class PackageManagementPackageReferenceEventArgs : EventArgs
+ {
+ public PackageManagementPackageReferenceEventArgs (Project project, string id, string version)
+ {
+ Project = project;
+ PackageReference = new PackageManagementPackageReference (id, version);
+ }
+
+ public Project Project { get; private set; }
+ public PackageManagementPackageReference PackageReference { get; private set; }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitor.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitor.cs index 74076d6d47..6b73844a49 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitor.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitor.cs @@ -1,4 +1,4 @@ -//
+//
// PackageManagementProgressMonitor.cs
//
// Author:
@@ -26,21 +26,21 @@ using System;
using System.Collections.Generic;
+using System.IO;
+using System.Linq;
using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
-using MonoDevelop.Core.ProgressMonitoring;
-using System.IO;
+using System.Threading;
namespace MonoDevelop.PackageManagement
{
- public class PackageManagementProgressMonitor : IProgressMonitor, IAsyncOperation
+ public class PackageManagementProgressMonitor : ProgressMonitor
{
- IProgressMonitor consoleMonitor;
- IProgressMonitor statusMonitor;
- List<string> warnings = new List<string> ();
- List<string> errors = new List<string> ();
+ ProgressMonitor consoleMonitor;
+ CancellationTokenRegistration consoleMonitorReg;
+ CancellationTokenRegistration statusMonitorReg;
- public IProgressMonitor ConsoleMonitor {
+ public ProgressMonitor ConsoleMonitor {
get { return consoleMonitor; }
}
@@ -48,146 +48,73 @@ namespace MonoDevelop.PackageManagement get { return (IConsole)this.consoleMonitor; }
}
- public PackageManagementProgressMonitor (IProgressMonitor consoleMonitor, IProgressMonitor statusMonitor)
+ public PackageManagementProgressMonitor (ProgressMonitor consoleMonitor, ProgressMonitor statusMonitor)
{
+ AddSlaveMonitor (statusMonitor);
this.consoleMonitor = consoleMonitor;
- this.statusMonitor = statusMonitor;
-
- consoleMonitor.CancelRequested += OnCancelRequested;
- statusMonitor.CancelRequested += OnCancelRequested;
- }
-
- public void BeginTask (string name, int totalWork)
- {
- statusMonitor.BeginTask (name, totalWork);
- }
-
- public void BeginStepTask (string name, int totalWork, int stepSize)
- {
- statusMonitor.BeginStepTask (name, totalWork, stepSize);
- }
- public void EndTask ()
- {
- statusMonitor.EndTask ();
+ consoleMonitorReg = consoleMonitor.CancellationToken.Register (OnCancelRequested);
+ statusMonitorReg = statusMonitor.CancellationToken.Register (OnCancelRequested);
}
- public void Step (int work)
+ protected override void OnWriteLog (string message)
{
- statusMonitor.Step (work);
+ consoleMonitor.Log.Write (message);
}
- public TextWriter Log
+ protected override void OnWriteErrorLog (string message)
{
- get { return consoleMonitor.Log; }
+ consoleMonitor.ErrorLog.Write (message);
}
- public void ReportSuccess (string message)
+ public override void Dispose ()
{
- consoleMonitor.ReportSuccess (message);
- statusMonitor.ReportSuccess (message);
- }
+ consoleMonitorReg.Dispose ();
+ statusMonitorReg.Dispose ();
- public void ReportWarning (string message)
- {
- warnings.Add (message);
- statusMonitor.ReportWarning (message);
- }
-
- public void ReportError (string message, Exception ex)
- {
- errors.Add (message);
- statusMonitor.ReportError (message, ex);
- }
-
- public void Dispose ()
- {
- consoleMonitor.CancelRequested -= OnCancelRequested;
- statusMonitor.CancelRequested -= OnCancelRequested;
+ foreach (var m in SuccessMessages)
+ consoleMonitor.ReportSuccess (m);
// Do not report warnings if there are errors otherwise the warnings will
// appear at the end of the Package Console and hide the error which
// should be the last line of text visible to the user.
- if (errors.Count == 0) {
+ if (Errors.Length == 0) {
ReportAllWarningsButLastToConsole ();
}
ReportAllErrorsButLastToConsole ();
consoleMonitor.Dispose ();
- statusMonitor.Dispose ();
}
void ReportAllWarningsButLastToConsole ()
{
+ var warnings = Warnings.Distinct ().ToList ();
RemoveLastItem (warnings);
warnings.ForEach (warning => consoleMonitor.ReportWarning (warning));
}
void ReportAllErrorsButLastToConsole ()
{
+ var errors = Errors.ToList ();
RemoveLastItem (errors);
- errors.ForEach (error => consoleMonitor.ReportError (error, null));
+ errors.ForEach (error => consoleMonitor.ReportError (error.Message, error.Exception));
}
- static void RemoveLastItem (List<string> items)
+ static void RemoveLastItem<T> (List<T> items)
{
if (items.Count > 0) {
items.RemoveAt (items.Count - 1);
}
}
- public bool IsCancelRequested
- {
- get {
- return consoleMonitor.IsCancelRequested || statusMonitor.IsCancelRequested;
- }
- }
-
public object SyncRoot {
get { return this; }
}
- void OnCancelRequested (IProgressMonitor sender)
- {
- AsyncOperation.Cancel ();
- }
-
- public IAsyncOperation AsyncOperation
- {
- get { return this; }
- }
-
- void IAsyncOperation.Cancel ()
- {
- consoleMonitor.AsyncOperation.Cancel ();
- }
-
- void IAsyncOperation.WaitForCompleted ()
+ void OnCancelRequested ()
{
- consoleMonitor.AsyncOperation.WaitForCompleted ();
- }
-
- public bool IsCompleted {
- get { return consoleMonitor.AsyncOperation.IsCompleted; }
- }
-
- bool IAsyncOperation.Success {
- get { return consoleMonitor.AsyncOperation.Success; }
- }
-
- bool IAsyncOperation.SuccessWithWarnings {
- get { return consoleMonitor.AsyncOperation.SuccessWithWarnings; }
- }
-
- public event MonitorHandler CancelRequested {
- add { consoleMonitor.CancelRequested += value; }
- remove { consoleMonitor.CancelRequested -= value; }
- }
-
- public event OperationHandler Completed {
- add { consoleMonitor.AsyncOperation.Completed += value; }
- remove { consoleMonitor.AsyncOperation.Completed -= value; }
+ CancellationTokenSource.Cancel ();
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitorFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitorFactory.cs index d15afde849..98dae1d2a6 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitorFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressMonitorFactory.cs @@ -34,13 +34,13 @@ namespace MonoDevelop.PackageManagement {
public class PackageManagementProgressMonitorFactory : IPackageManagementProgressMonitorFactory
{
- public IProgressMonitor CreateProgressMonitor (string title)
+ public ProgressMonitor CreateProgressMonitor (string title)
{
- IProgressMonitor consoleMonitor = CreatePackageConsoleOutputMonitor ();
+ ProgressMonitor consoleMonitor = CreatePackageConsoleOutputMonitor ();
Pad pad = IdeApp.Workbench.ProgressMonitors.GetPadForMonitor (consoleMonitor);
- IProgressMonitor statusMonitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor (
+ ProgressMonitor statusMonitor = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor (
title,
Stock.StatusSolutionOperation,
false,
@@ -51,7 +51,7 @@ namespace MonoDevelop.PackageManagement return new PackageManagementProgressMonitor (consoleMonitor, statusMonitor);
}
- IProgressMonitor CreatePackageConsoleOutputMonitor ()
+ ProgressMonitor CreatePackageConsoleOutputMonitor ()
{
return IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor (
"PackageConsole",
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressProvider.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressProvider.cs index 4c2353b194..5ca37f109a 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressProvider.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProgressProvider.cs @@ -36,7 +36,7 @@ namespace MonoDevelop.PackageManagement Action<MessageHandler> guiDispatcher;
public PackageManagementProgressProvider (IPackageRepositoryFactoryEvents repositoryFactoryEvents)
- : this (repositoryFactoryEvents, DispatchService.GuiDispatch)
+ : this (repositoryFactoryEvents, h => DispatchService.GuiDispatch (h))
{
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProject.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProject.cs index d5a036502b..2aa0377574 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProject.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProject.cs @@ -253,5 +253,15 @@ namespace ICSharpCode.PackageManagement {
return projectManager.LocalRepository.Exists (packageReference.Id, packageReference.Version);
}
+
+ public IPackageConstraintProvider ConstraintProvider {
+ get {
+ var constraintProvider = projectManager.LocalRepository as IPackageConstraintProvider;
+ if (constraintProvider != null) {
+ return constraintProvider;
+ }
+ return NullConstraintProvider.Instance;
+ }
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProjectOperations.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProjectOperations.cs new file mode 100644 index 0000000000..b550cf2910 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementProjectOperations.cs @@ -0,0 +1,151 @@ +//
+// PackageManagementProjectOperations.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.PackageManagement;
+using MonoDevelop.Ide;
+using MonoDevelop.Projects;
+using NuGet;
+
+namespace MonoDevelop.PackageManagement
+{
+ public class PackageManagementProjectOperations : IPackageManagementProjectOperations
+ {
+ IPackageManagementSolution solution;
+ IRegisteredPackageRepositories registeredPackageRepositories;
+ BackgroundPackageActionRunner backgroundActionRunner;
+ IPackageManagementEvents packageManagementEvents;
+
+ public PackageManagementProjectOperations (
+ IPackageManagementSolution solution,
+ IRegisteredPackageRepositories registeredPackageRepositories,
+ BackgroundPackageActionRunner backgroundActionRunner,
+ IPackageManagementEvents packageManagementEvents)
+ {
+ this.solution = solution;
+ this.registeredPackageRepositories = registeredPackageRepositories;
+ this.backgroundActionRunner = backgroundActionRunner;
+ this.packageManagementEvents = packageManagementEvents;
+
+ packageManagementEvents.ParentPackageInstalled += PackageInstalled;
+ packageManagementEvents.ParentPackageUninstalled += PackageUninstalled;
+ }
+
+ public event EventHandler<PackageManagementPackageReferenceEventArgs> PackageReferenceAdded;
+ public event EventHandler<PackageManagementPackageReferenceEventArgs> PackageReferenceRemoved;
+
+ public void InstallPackages (
+ string packageSourceUrl,
+ Project project,
+ IEnumerable<PackageManagementPackageReference> packages)
+ {
+ List<IPackageAction> actions = null;
+
+ DispatchService.GuiSyncDispatch (() => {
+ IPackageRepository repository = CreatePackageRepository (packageSourceUrl);
+ IPackageManagementProject packageManagementProject = solution.GetProject (repository, new DotNetProjectProxy ((DotNetProject)project));
+ actions = packages.Select (packageReference => {
+ InstallPackageAction action = packageManagementProject.CreateInstallPackageAction ();
+ action.PackageId = packageReference.Id;
+ action.PackageVersion = new SemanticVersion (packageReference.Version);
+ return (IPackageAction)action;
+ }).ToList ();
+ });
+
+ ProgressMonitorStatusMessage progressMessage = GetProgressMonitorStatusMessages (actions);
+ backgroundActionRunner.RunAndWait (progressMessage, actions);
+ }
+
+ IPackageRepository CreatePackageRepository (string packageSourceUrl)
+ {
+ IPackageRepository repository = registeredPackageRepositories.CreateRepository (new PackageSource (packageSourceUrl));
+ return new PriorityPackageRepository (MachineCache.Default, repository);
+ }
+
+ ProgressMonitorStatusMessage GetProgressMonitorStatusMessages (List<IPackageAction> packageActions)
+ {
+ if (packageActions.Count == 1) {
+ string packageId = packageActions.OfType<ProcessPackageAction> ().First ().PackageId;
+ return ProgressMonitorStatusMessageFactory.CreateInstallingSinglePackageMessage (packageId);
+ }
+ return ProgressMonitorStatusMessageFactory.CreateInstallingMultiplePackagesMessage (packageActions.Count);
+ }
+
+ public IEnumerable<PackageManagementPackageReference> GetInstalledPackages (Project project)
+ {
+ List<PackageManagementPackageReference> packageReferences = null;
+
+ DispatchService.GuiSyncDispatch (() => {
+ string url = RegisteredPackageSources.DefaultPackageSourceUrl;
+ var repository = registeredPackageRepositories.CreateRepository (new PackageSource (url));
+ IPackageManagementProject packageManagementProject = solution.GetProject (repository, new DotNetProjectProxy ((DotNetProject)project));
+ packageReferences = packageManagementProject
+ .GetPackageReferences ()
+ .Select (packageReference => new PackageManagementPackageReference (packageReference.Id, packageReference.Version.ToString ()))
+ .ToList ();
+ });
+
+ return packageReferences;
+ }
+
+ void PackageUninstalled (object sender, ParentPackageOperationEventArgs e)
+ {
+ OnPackageReferencedRemoved (e);
+ }
+
+ void PackageInstalled (object sender, ParentPackageOperationEventArgs e)
+ {
+ OnPackageReferenceAdded (e);
+ }
+
+ void OnPackageReferencedRemoved (ParentPackageOperationEventArgs e)
+ {
+ var handler = PackageReferenceRemoved;
+ if (handler != null) {
+ handler (this, CreateEventArgs (e));
+ }
+ }
+
+ void OnPackageReferenceAdded (ParentPackageOperationEventArgs e)
+ {
+ var handler = PackageReferenceAdded;
+ if (handler != null) {
+ handler (this, CreateEventArgs (e));
+ }
+ }
+
+ PackageManagementPackageReferenceEventArgs CreateEventArgs (ParentPackageOperationEventArgs e)
+ {
+ return new PackageManagementPackageReferenceEventArgs (
+ e.Project.DotNetProject,
+ e.Package.Id,
+ e.Package.Version.ToString ());
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementServices.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementServices.cs index 30670dbd14..ccf2cb438c 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementServices.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementServices.cs @@ -29,6 +29,7 @@ using System;
using NuGet;
using MonoDevelop.PackageManagement;
+using MonoDevelop.Core;
namespace ICSharpCode.PackageManagement
{
@@ -49,8 +50,9 @@ namespace ICSharpCode.PackageManagement static readonly IPackageManagementProgressMonitorFactory progressMonitorFactory;
static readonly PackageManagementProgressProvider progressProvider;
static readonly ProjectTargetFrameworkMonitor projectTargetFrameworkMonitor;
- static readonly PackageCompatibilityHandler packageCompatibilityHander;
+ static readonly PackageCompatibilityHandler packageCompatibilityHandler;
static readonly UpdatedPackagesInSolution updatedPackagesInSolution;
+ static readonly PackageManagementProjectOperations projectOperations;
static PackageManagementServices()
{
@@ -71,10 +73,13 @@ namespace ICSharpCode.PackageManagement backgroundPackageActionRunner = new BackgroundPackageActionRunner (progressMonitorFactory, packageManagementEvents, progressProvider);
projectTargetFrameworkMonitor = new ProjectTargetFrameworkMonitor (projectService);
- packageCompatibilityHander = new PackageCompatibilityHandler (projectTargetFrameworkMonitor);
+ packageCompatibilityHandler = new PackageCompatibilityHandler ();
+ packageCompatibilityHandler.MonitorTargetFrameworkChanges (projectTargetFrameworkMonitor);
updatedPackagesInSolution = new UpdatedPackagesInSolution (solution, registeredPackageRepositories, packageManagementEvents);
+ projectOperations = new PackageManagementProjectOperations (solution, registeredPackageRepositories, backgroundPackageActionRunner, packageManagementEvents);
+
InitializeCredentialProvider();
}
@@ -85,11 +90,21 @@ namespace ICSharpCode.PackageManagement static SettingsCredentialProvider CreateSettingsCredentialProvider (ICredentialProvider credentialProvider)
{
- ISettings settings = Settings.LoadDefaultSettings (null, null, null);
+ ISettings settings = LoadSettings ();
var packageSourceProvider = new PackageSourceProvider (settings);
return new SettingsCredentialProvider(credentialProvider, packageSourceProvider);
}
+ static ISettings LoadSettings ()
+ {
+ try {
+ return Settings.LoadDefaultSettings (null, null, null);
+ } catch (Exception ex) {
+ LoggingService.LogInternalError ("Unable to load NuGet.Config.", ex);
+ }
+ return NullSettings.Instance;
+ }
+
public static PackageManagementOptions Options {
get { return options; }
}
@@ -149,5 +164,9 @@ namespace ICSharpCode.PackageManagement public static IUpdatedPackagesInSolution UpdatedPackagesInSolution {
get { return updatedPackagesInSolution; }
}
+
+ public static IPackageManagementProjectOperations ProjectOperations {
+ get { return projectOperations; }
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementSolution.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementSolution.cs index eaed7d4ed3..f732ecd211 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementSolution.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageManagementSolution.cs @@ -214,5 +214,10 @@ namespace ICSharpCode.PackageManagement yield return CreateProject (sourceRepository, dotNetProject);
}
}
+
+ public ISolutionPackageRepository GetRepository ()
+ {
+ return CreateSolutionPackageRepository ();
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRepositoryCache.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRepositoryCache.cs index 0315f4530a..ca1ae8b41d 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRepositoryCache.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRepositoryCache.cs @@ -29,6 +29,7 @@ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using MonoDevelop.PackageManagement;
using NuGet;
namespace ICSharpCode.PackageManagement
@@ -40,17 +41,30 @@ namespace ICSharpCode.PackageManagement PackageManagementOptions options;
IList<RecentPackageInfo> recentPackages;
IRecentPackageRepository recentPackageRepository;
+ IPackageRepository machineCache;
ConcurrentDictionary<string, IPackageRepository> repositories =
new ConcurrentDictionary<string, IPackageRepository>();
public PackageRepositoryCache (
PackageManagementOptions options,
+ IPackageRepository machineCache,
ISharpDevelopPackageRepositoryFactory factory)
{
this.options = options;
+ this.machineCache = machineCache;
this.factory = factory;
this.recentPackages = options.RecentPackages;
}
+
+ public PackageRepositoryCache (
+ PackageManagementOptions options,
+ ISharpDevelopPackageRepositoryFactory factory)
+ : this (
+ options,
+ MachineCache.Default,
+ factory)
+ {
+ }
public PackageRepositoryCache (PackageManagementOptions options)
: this(
@@ -119,7 +133,7 @@ namespace ICSharpCode.PackageManagement IEnumerable<IPackageRepository> CreateAllEnabledRepositories()
{
foreach (PackageSource source in PackageSources.GetEnabledPackageSources ()) {
- yield return CreateRepository(source.Source);
+ yield return CreateRepositoryIgnoringFailures (source.Source);
}
}
@@ -160,5 +174,23 @@ namespace ICSharpCode.PackageManagement }
return recentPackageRepository;
}
+
+ public IPackageRepository CreateAggregateWithPriorityMachineCacheRepository ()
+ {
+ return new PriorityPackageRepository (machineCache, CreateAggregateRepository ());
+ }
+
+ IPackageRepository CreateRepositoryIgnoringFailures (string packageSource)
+ {
+ try {
+ return CreateRepository (packageSource);
+ } catch (Exception ex) {
+ // Deliberately caching the failing package source so the
+ // AggregateRepository only reports its failure once.
+ var repository = new FailingPackageRepository (packageSource, ex);
+ repositories.TryAdd(packageSource, repository);
+ return repository;
+ }
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestoreRunner.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestoreRunner.cs index dbf9d5af71..eb919868c7 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestoreRunner.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestoreRunner.cs @@ -1,4 +1,4 @@ -//
+//
// PackageRestoreRunner.cs
//
// Author:
@@ -33,6 +33,7 @@ using MonoDevelop.Ide; using MonoDevelop.Ide.Gui;
using MonoDevelop.Core.ProgressMonitoring;
using MonoDevelop.Projects;
+using NuGet;
namespace MonoDevelop.PackageManagement
{
@@ -41,23 +42,28 @@ namespace MonoDevelop.PackageManagement IPackageManagementSolution solution;
IPackageManagementProgressMonitorFactory progressMonitorFactory;
IPackageManagementEvents packageManagementEvents;
+ IProgressProvider progressProvider;
+ IDotNetProject project;
public PackageRestoreRunner()
: this(
PackageManagementServices.Solution,
PackageManagementServices.ProgressMonitorFactory,
- PackageManagementServices.PackageManagementEvents)
+ PackageManagementServices.PackageManagementEvents,
+ PackageManagementServices.ProgressProvider)
{
}
public PackageRestoreRunner(
IPackageManagementSolution solution,
IPackageManagementProgressMonitorFactory progressMonitorFactory,
- IPackageManagementEvents packageManagementEvents)
+ IPackageManagementEvents packageManagementEvents,
+ IProgressProvider progressProvider)
{
this.solution = solution;
this.progressMonitorFactory = progressMonitorFactory;
this.packageManagementEvents = packageManagementEvents;
+ this.progressProvider = progressProvider;
}
public void Run ()
@@ -65,72 +71,55 @@ namespace MonoDevelop.PackageManagement Run (ProgressMonitorStatusMessageFactory.CreateRestoringPackagesInSolutionMessage ());
}
+ public void Run (IDotNetProject project, ProgressMonitorStatusMessage progressMessage)
+ {
+ this.project = project;
+ Run (progressMessage);
+ }
+
public void Run (ProgressMonitorStatusMessage progressMessage)
{
- IProgressMonitor progressMonitor = CreateProgressMonitor (progressMessage);
-
- try {
- RestorePackages(progressMonitor, progressMessage);
- } catch (Exception ex) {
- LoggingService.LogInternalError (ex);
- progressMonitor.Log.WriteLine(ex.Message);
- progressMonitor.ReportError (progressMessage.Error, null);
- progressMonitor.ShowPackageConsole ();
- progressMonitor.Dispose();
- RestoreFailed = true;
+ using (ProgressMonitor progressMonitor = CreateProgressMonitor (progressMessage)) {
+ using (PackageManagementEventsMonitor eventMonitor = CreateEventMonitor (progressMonitor)) {
+ try {
+ RestorePackages (progressMonitor, progressMessage);
+ } catch (Exception ex) {
+ LoggingService.LogInternalError (ex);
+ progressMonitor.Log.WriteLine (ex.Message);
+ progressMonitor.ReportError (progressMessage.Error, null);
+ progressMonitor.ShowPackageConsole ();
+ progressMonitor.Dispose ();
+ RestoreFailed = true;
+ }
+ }
}
}
public bool RestoreFailed { get; private set; }
- IProgressMonitor CreateProgressMonitor (ProgressMonitorStatusMessage progressMessage)
+ ProgressMonitor CreateProgressMonitor (ProgressMonitorStatusMessage progressMessage)
{
return progressMonitorFactory.CreateProgressMonitor (progressMessage.Status);
}
- void RestorePackages(IProgressMonitor progressMonitor, ProgressMonitorStatusMessage progressMessage)
+ PackageManagementEventsMonitor CreateEventMonitor (ProgressMonitor monitor)
{
- var commandLine = new NuGetPackageRestoreCommandLine(solution);
-
- progressMonitor.Log.WriteLine(commandLine.ToString());
-
- RestorePackages(progressMonitor, progressMessage, commandLine);
+ return new PackageManagementEventsMonitor (monitor, packageManagementEvents, progressProvider);
}
- void RestorePackages(
- IProgressMonitor progressMonitor,
- ProgressMonitorStatusMessage progressMessage,
- NuGetPackageRestoreCommandLine commandLine)
+ void RestorePackages (ProgressMonitor progressMonitor, ProgressMonitorStatusMessage progressMessage)
{
- var aggregatedMonitor = (PackageManagementProgressMonitor)progressMonitor;
-
- IProcessAsyncOperation operation = Runtime.ProcessService.StartConsoleProcess (
- commandLine.Command,
- commandLine.Arguments,
- commandLine.WorkingDirectory,
- aggregatedMonitor.Console,
- (sender, e) => {
- using (progressMonitor) {
- OnPackageRestoreCompleted ((IAsyncOperation)sender, progressMonitor, progressMessage);
- }
- }
- );
+ var action = new RestorePackagesAction (solution, packageManagementEvents);
+ if (project != null) {
+ action.Project = project;
+ }
+ action.Execute ();
- // Wait for console to finish just so check for updates does not run until
- // all packages are restored.
- operation.WaitForCompleted ();
- }
+ RefreshProjectReferences ();
+ ForceCreationOfSharedRepositoriesConfigFile ();
- void OnPackageRestoreCompleted (
- IAsyncOperation operation,
- IProgressMonitor progressMonitor,
- ProgressMonitorStatusMessage progressMessage)
- {
- if (operation.Success) {
- RefreshProjectReferences ();
- ForceCreationOfSharedRepositoriesConfigFile ();
- }
- ReportOutcome (operation, progressMonitor, progressMessage);
+ progressMonitor.ReportSuccess (progressMessage.Success);
+ packageManagementEvents.OnPackagesRestored ();
}
/// <summary>
@@ -143,32 +132,18 @@ namespace MonoDevelop.PackageManagement solution.GetProjects (repository).ToList ();
}
+ /// <summary>
+ /// Refresh all projects even though we may have only restored packages for one project since
+ /// the packages may be used in other projects.
+ /// </summary>
void RefreshProjectReferences ()
{
DispatchService.GuiDispatch (() => {
- Solution solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
- if (solution != null) {
- foreach (DotNetProject project in solution.GetAllDotNetProjects ()) {
- project.RefreshReferenceStatus ();
- }
+ foreach (IDotNetProject projectInSolution in solution.GetDotNetProjects ()) {
+ projectInSolution.DotNetProject.RefreshReferenceStatus ();
}
});
}
-
- void ReportOutcome (
- IAsyncOperation operation,
- IProgressMonitor progressMonitor,
- ProgressMonitorStatusMessage progressMessage)
- {
- if (operation.Success) {
- progressMonitor.ReportSuccess (progressMessage.Success);
- packageManagementEvents.OnPackagesRestored ();
- } else {
- progressMonitor.ReportError (progressMessage.Error, null);
- progressMonitor.ShowPackageConsole ();
- RestoreFailed = true;
- }
- }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestorer.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestorer.cs index da8eba3d32..912e981ecc 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestorer.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageRestorer.cs @@ -38,6 +38,7 @@ namespace MonoDevelop.PackageManagement public class PackageRestorer
{
List<ProjectPackageReferenceFile> packageReferenceFiles;
+ IDotNetProject singleProject;
public PackageRestorer (Solution solution)
: this (solution.GetAllDotNetProjects ())
@@ -47,6 +48,7 @@ namespace MonoDevelop.PackageManagement public PackageRestorer (DotNetProject project)
: this (new [] { project })
{
+ singleProject = new DotNetProjectProxy (project);
}
public PackageRestorer (IEnumerable<DotNetProject> projects)
@@ -88,7 +90,11 @@ namespace MonoDevelop.PackageManagement void RestoreWithProgressMonitor (ProgressMonitorStatusMessage progressMessage)
{
var runner = new PackageRestoreRunner ();
- runner.Run (progressMessage);
+ if (singleProject != null) {
+ runner.Run (singleProject, progressMessage);
+ } else {
+ runner.Run (progressMessage);
+ }
RestoreFailed = runner.RestoreFailed;
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdateChecker.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdateChecker.cs index 78c67ca0bb..8850375e3e 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdateChecker.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdateChecker.cs @@ -62,10 +62,10 @@ namespace MonoDevelop.PackageManagement void CheckForPackageUpdatesWithProgressMonitor ()
{
ProgressMonitorStatusMessage progressMessage = ProgressMonitorStatusMessageFactory.CreateCheckingForPackageUpdatesMessage ();
- using (IProgressMonitor progressMonitor = CreateProgressMonitor (progressMessage)) {
+ using (ProgressMonitor progressMonitor = CreateProgressMonitor (progressMessage)) {
try {
- using (IDisposable eventMonitor = new PackageUpdatesEventMonitor (progressMonitor)) {
- CheckForPackageUpdates (progressMonitor, progressMessage);
+ using (var eventMonitor = new PackageUpdatesEventMonitor (progressMonitor)) {
+ CheckForPackageUpdates (progressMonitor, progressMessage, eventMonitor);
}
} catch (Exception ex) {
LoggingService.LogInternalError (ex);
@@ -76,16 +76,21 @@ namespace MonoDevelop.PackageManagement }
}
- IProgressMonitor CreateProgressMonitor (ProgressMonitorStatusMessage progressMessage)
+ ProgressMonitor CreateProgressMonitor (ProgressMonitorStatusMessage progressMessage)
{
return progressMonitorFactory.CreateProgressMonitor (progressMessage.Status);
}
- void CheckForPackageUpdates (IProgressMonitor progressMonitor, ProgressMonitorStatusMessage progressMessage)
+ void CheckForPackageUpdates (
+ ProgressMonitor progressMonitor,
+ ProgressMonitorStatusMessage progressMessage,
+ PackageUpdatesEventMonitor eventMonitor)
{
updatedPackagesInSolution.CheckForUpdates ();
if (updatedPackagesInSolution.AnyUpdates ()) {
progressMonitor.ReportSuccess (GettextCatalog.GetString ("Package updates are available."));
+ } else if (eventMonitor.WarningReported) {
+ progressMonitor.ReportWarning (progressMessage.Warning);
} else {
progressMonitor.ReportSuccess (progressMessage.Success);
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdatesEventMonitor.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdatesEventMonitor.cs index 472aacdcef..4957c8b673 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdatesEventMonitor.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackageUpdatesEventMonitor.cs @@ -27,15 +27,16 @@ using System;
using ICSharpCode.PackageManagement;
using MonoDevelop.Core;
+using NuGet;
namespace MonoDevelop.PackageManagement
{
public class PackageUpdatesEventMonitor : IDisposable
{
IPackageManagementEvents packageEvents;
- IProgressMonitor progressMonitor;
+ ProgressMonitor progressMonitor;
- public PackageUpdatesEventMonitor (IProgressMonitor progressMonitor)
+ public PackageUpdatesEventMonitor (ProgressMonitor progressMonitor)
: this (
progressMonitor,
PackageManagementServices.PackageManagementEvents)
@@ -43,7 +44,7 @@ namespace MonoDevelop.PackageManagement }
public PackageUpdatesEventMonitor (
- IProgressMonitor progressMonitor,
+ ProgressMonitor progressMonitor,
IPackageManagementEvents packageEvents)
{
this.progressMonitor = progressMonitor;
@@ -55,13 +56,18 @@ namespace MonoDevelop.PackageManagement void PackageOperationMessageLogged (object sender, PackageOperationMessageLoggedEventArgs e)
{
progressMonitor.Log.WriteLine (e.Message.ToString ());
+
+ if (e.Message.Level == MessageLevel.Warning) {
+ WarningReported = true;
+ }
}
public void Dispose ()
{
packageEvents.PackageOperationMessageLogged -= PackageOperationMessageLogged;
}
- }
+ public bool WarningReported { get; private set; }
+ }
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModel.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModel.cs index 3c2934d1d8..86b2ed48c8 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModel.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModel.cs @@ -124,7 +124,7 @@ namespace ICSharpCode.PackageManagement void StartReadPackagesTask(bool clearPackages = true)
{
IsReadingPackages = true;
- HasError = false;
+ ClearError ();
if (clearPackages) {
ClearPackages ();
}
@@ -132,6 +132,12 @@ namespace ICSharpCode.PackageManagement CreateReadPackagesTask();
task.Start();
}
+
+ void ClearError ()
+ {
+ HasError = false;
+ ErrorMessage = String.Empty;
+ }
protected virtual void UpdateRepositoryBeforeReadPackagesTaskStarts()
{
@@ -170,6 +176,7 @@ namespace ICSharpCode.PackageManagement // Ignore.
return;
} else {
+ SaveAnyWarnings ();
UpdatePackagesForSelectedPage(task.Result);
}
base.OnPropertyChanged(null);
@@ -193,6 +200,20 @@ namespace ICSharpCode.PackageManagement return errorMessage.ToString();
}
+ void SaveAnyWarnings ()
+ {
+ string warning = GetWarningMessage ();
+ if (!String.IsNullOrEmpty (warning)) {
+ HasError = true;
+ ErrorMessage = warning;
+ }
+ }
+
+ protected virtual string GetWarningMessage ()
+ {
+ return String.Empty;
+ }
+
void UpdatePackagesForSelectedPage(PackagesForSelectedPageResult result)
{
pages.TotalItems = result.TotalPackages;
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModels.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModels.cs index 2bf7ad3e67..f93581a5ab 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModels.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PackagesViewModels.cs @@ -44,7 +44,7 @@ namespace ICSharpCode.PackageManagement //var installedPackageViewModelFactory = new InstalledPackageViewModelFactory(packageViewModelFactory);
IRecentPackageRepository recentPackageRepository = PackageManagementServices.RecentPackageRepository;
- AvailablePackagesViewModel = new AvailablePackagesViewModel(registeredPackageRepositories, recentPackageRepository, packageViewModelFactory, taskFactory);
+ AvailablePackagesViewModel = new AvailablePackagesViewModel (solution, registeredPackageRepositories, recentPackageRepository, packageViewModelFactory, taskFactory);
//InstalledPackagesViewModel = new InstalledPackagesViewModel(solution, packageManagementEvents, registeredPackageRepositories, installedPackageViewModelFactory, taskFactory);
//UpdatedPackagesViewModel = new UpdatedPackagesViewModel(solution, registeredPackageRepositories, updatedPackageViewModelFactory, taskFactory);
//RecentPackagesViewModel = new RecentPackagesViewModel(packageManagementEvents, registeredPackageRepositories, packageViewModelFactory, taskFactory);
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PreventPackagesConfigFileBeingRemovedOnUpdateMonitor.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PreventPackagesConfigFileBeingRemovedOnUpdateMonitor.cs new file mode 100644 index 0000000000..07345ba0a2 --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/PreventPackagesConfigFileBeingRemovedOnUpdateMonitor.cs @@ -0,0 +1,71 @@ +//
+// PreventPackagesConfigFileBeingRemovedOnUpdateMonitor.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using ICSharpCode.PackageManagement;
+using System.IO;
+using MonoDevelop.Core;
+
+namespace MonoDevelop.PackageManagement
+{
+ /// <summary>
+ /// When updating a package the packages.config file may be removed, if all packages are
+ /// uninstalled during the update, which causes the version control system to mark the file as
+ /// deleted. During an update the packages.config file will be recreated so the version control
+ /// system should not mark it as deleted. This monitor class looks for the packages.config file
+ /// being removed, cancels the standard file deletion call to FileService.RemoveFile, and
+ /// removes the file itself.
+ /// </summary>
+ public class PreventPackagesConfigFileBeingRemovedOnUpdateMonitor : IDisposable
+ {
+ IPackageManagementEvents packageManagementEvents;
+ IFileRemover fileRemover;
+
+ public PreventPackagesConfigFileBeingRemovedOnUpdateMonitor (
+ IPackageManagementEvents packageManagementEvents,
+ IFileRemover fileRemover)
+ {
+ this.packageManagementEvents = packageManagementEvents;
+ this.fileRemover = fileRemover;
+
+ packageManagementEvents.FileRemoving += FileRemoving;
+ }
+
+ void FileRemoving (object sender, FileRemovingEventArgs e)
+ {
+ if (e.FileName.IsPackagesConfigFileName ()) {
+ e.IsCancelled = true;
+ fileRemover.RemoveFile (e.FileName);
+ }
+ }
+
+ public void Dispose ()
+ {
+ packageManagementEvents.FileRemoving -= FileRemoving;
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProcessPackageAction.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProcessPackageAction.cs index 53d3b33c81..a17603c744 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProcessPackageAction.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProcessPackageAction.cs @@ -218,7 +218,12 @@ namespace ICSharpCode.PackageManagement {
Package = Project
.SourceRepository
- .FindPackage(PackageId, PackageVersion, AllowPrereleaseVersions, allowUnlisted: false);
+ .FindPackage (
+ PackageId,
+ PackageVersion,
+ Project.ConstraintProvider,
+ AllowPrereleaseVersions,
+ allowUnlisted: false);
}
void ThrowPackageNotFoundError(string packageId)
@@ -233,12 +238,20 @@ namespace ICSharpCode.PackageManagement return Project.IsPackageInstalled(id);
}
- string GetPackageId()
+ public string GetPackageId ()
{
if (Package != null) {
return Package.Id;
}
return PackageId;
}
+
+ public SemanticVersion GetPackageVersion ()
+ {
+ if (Package != null) {
+ return Package.Version;
+ }
+ return PackageVersion;
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorExtensions.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorExtensions.cs index 6054ce7cf4..6474b90952 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorExtensions.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorExtensions.cs @@ -34,7 +34,7 @@ namespace MonoDevelop.PackageManagement {
public static class ProgressMonitorExtensions
{
- public static void ShowPackageConsole (this IProgressMonitor monitor)
+ public static void ShowPackageConsole (this ProgressMonitor monitor)
{
DispatchService.GuiDispatch (() => {
var aggregatedMonitor = (PackageManagementProgressMonitor)monitor;
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorStatusMessageFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorStatusMessageFactory.cs index 7de966f3a8..ae73cdb840 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorStatusMessageFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProgressMonitorStatusMessageFactory.cs @@ -163,6 +163,16 @@ namespace MonoDevelop.PackageManagement );
}
+ public static ProgressMonitorStatusMessage CreateRestoringPackagesInProjectMessage ()
+ {
+ return new ProgressMonitorStatusMessage (
+ GetString ("Restoring packages for project..."),
+ GetString ("Packages successfully restored."),
+ GetString ("Could not restore packages. Please see Package Console for details."),
+ GetString ("Packages restored with warnings. Please see Package Console for details.")
+ );
+ }
+
public static ProgressMonitorStatusMessage CreateCheckingPackageCompatibilityMessage ()
{
return new ProgressMonitorStatusMessage (
@@ -209,7 +219,7 @@ namespace MonoDevelop.PackageManagement GetString ("Checking for package updates..."),
GetString ("Packages are up to date."),
GetString ("Could not check for package updates. Please see Package Console for details."),
- String.Empty);
+ GetString ("No updates found but warnings were reported. Please see Package Console for details."));
}
static string GetString (string phrase)
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectExtensions.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectExtensions.cs index d04a5b35f4..a75fe987ca 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectExtensions.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectExtensions.cs @@ -38,7 +38,7 @@ namespace ICSharpCode.PackageManagement public static void Save(this Project project)
{
DispatchService.GuiSyncDispatch(() => {
- IdeApp.ProjectOperations.Save(project);
+ IdeApp.ProjectOperations.SaveAsync(project);
});
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectProxy.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectProxy.cs index 7aef3277df..763b683343 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectProxy.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectProxy.cs @@ -29,6 +29,7 @@ using System.Collections; using ICSharpCode.PackageManagement;
using MonoDevelop.Core;
using MonoDevelop.Projects;
+using System.Collections.Generic;
namespace MonoDevelop.PackageManagement
{
@@ -61,6 +62,10 @@ namespace MonoDevelop.PackageManagement get { return project.ExtendedProperties; }
}
+ public IEnumerable<string> FlavorGuids {
+ get { return project.FlavorGuids; }
+ }
+
public void Save ()
{
project.Save ();
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplateNuGetPackageInstaller.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplateNuGetPackageInstaller.cs index 5197bcba90..03884b65c7 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplateNuGetPackageInstaller.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplateNuGetPackageInstaller.cs @@ -61,6 +61,9 @@ namespace MonoDevelop.PackageManagement public override void Run (Solution solution, IList<PackageReferencesForCreatedProject> packageReferencesForCreatedProjects)
{
List<IPackageAction> installPackageActions = CreatePackageActions (solution, packageReferencesForCreatedProjects);
+ if (!installPackageActions.Any ())
+ return;
+
ProgressMonitorStatusMessage progressMessage = ProgressMonitorStatusMessageFactory.CreateInstallingProjectTemplatePackagesMessage ();
backgroundPackageActionRunner.Run (progressMessage, installPackageActions);
}
@@ -79,7 +82,7 @@ namespace MonoDevelop.PackageManagement var installPackageActions = new List<IPackageAction> ();
foreach (PackageReferencesForCreatedProject packageReferences in packageReferencesForCreatedProjects) {
- var project = solution.GetAllProjects ().First (p => p.Name == packageReferences.ProjectName) as DotNetProject;
+ var project = solution.GetAllProjects ().FirstOrDefault (p => p.Name == packageReferences.ProjectName) as DotNetProject;
if (project != null) {
installPackageActions.AddRange (CreateInstallPackageActions (project, packageReferences));
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplatePackageRepositoryCache.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplatePackageRepositoryCache.cs index 5b546e5d09..d6e695b431 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplatePackageRepositoryCache.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ProjectTemplatePackageRepositoryCache.cs @@ -86,5 +86,10 @@ namespace ICSharpCode.PackageManagement {
return packageRepositoryCache.CreateRepository(packageSource);
}
+
+ public IPackageRepository CreateAggregateWithPriorityMachineCacheRepository ()
+ {
+ throw new NotImplementedException ();
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RecentPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RecentPackageRepository.cs index f2e8b14cc8..b8c869ebc1 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RecentPackageRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RecentPackageRepository.cs @@ -117,6 +117,7 @@ namespace ICSharpCode.PackageManagement public IQueryable<IPackage> GetPackages()
{
//UpdatePackages();
+ RemoveInvalidPackages ();
return packages.AsQueryable();
}
@@ -127,6 +128,17 @@ namespace ICSharpCode.PackageManagement packages.AddRange(recentPackages);
}
}
+
+ void RemoveInvalidPackages ()
+ {
+ packages.RemoveAll (package => !IsValidPackage (package));
+ }
+
+ static bool IsValidPackage (IPackage package)
+ {
+ var packageFromRepository = package as IPackageFromRepository;
+ return (packageFromRepository != null) && packageFromRepository.IsValid;
+ }
bool HasRecentPackagesBeenRead()
{
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RegisteredPackageRepositories.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RegisteredPackageRepositories.cs index c326c47d1b..fcc7f64264 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RegisteredPackageRepositories.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RegisteredPackageRepositories.cs @@ -37,7 +37,6 @@ namespace ICSharpCode.PackageManagement {
IPackageRepositoryCache repositoryCache;
PackageManagementOptions options;
- RegisteredPackageSources registeredPackageSources;
PackageSource activePackageSource;
IPackageRepository activePackageRepository;
@@ -47,7 +46,6 @@ namespace ICSharpCode.PackageManagement {
this.repositoryCache = repositoryCache;
this.options = options;
- registeredPackageSources = options.PackageSources;
}
public IRecentPackageRepository RecentPackageRepository {
@@ -69,7 +67,7 @@ namespace ICSharpCode.PackageManagement }
public bool HasMultiplePackageSources {
- get { return registeredPackageSources.HasMultipleEnabledPackageSources; }
+ get { return PackageSources.HasMultipleEnabledPackageSources; }
}
public PackageSource ActivePackageSource {
@@ -122,6 +120,7 @@ namespace ICSharpCode.PackageManagement }
UpdateActivePackageSource ();
+ UpdateActivePackageRepository ();
} catch (Exception) {
PackageSources.AddRange (packageSourcesBackup);
UpdateActivePackageSource ();
@@ -149,5 +148,17 @@ namespace ICSharpCode.PackageManagement }
}
}
+
+ void UpdateActivePackageRepository ()
+ {
+ if (activePackageSource == null)
+ return;
+
+ if (activePackageSource.IsAggregate ()) {
+ // Force recreation of AggregateRepository to reset any
+ // failing package repositories.
+ activePackageRepository = null;
+ }
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RestoreBeforeUpdateAction.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RestoreBeforeUpdateAction.cs index 154e67ee5f..3d3c5ce64c 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RestoreBeforeUpdateAction.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RestoreBeforeUpdateAction.cs @@ -57,7 +57,8 @@ namespace MonoDevelop.PackageManagement IPackageManagementProject project,
Action afterRestore)
{
- Restore (new [] { project }, afterRestore);
+ var runner = new RestoreBeforeUpdateAction ();
+ runner.RestoreProjectPackages (project.DotNetProject, afterRestore);
}
public static void Restore (
@@ -65,18 +66,23 @@ namespace MonoDevelop.PackageManagement Action afterRestore)
{
var runner = new RestoreBeforeUpdateAction ();
- runner.RestoreProjectPackages (
+ runner.RestoreAllPackagesInSolution (
projects.Select (project => project.DotNetProject),
afterRestore);
}
- public void RestoreProjectPackages (
+ public void RestoreAllPackagesInSolution (
IEnumerable<DotNetProject> projects,
Action afterRestore)
{
+ var restorer = new PackageRestorer (projects);
+ Restore (restorer, afterRestore);
+ }
+
+ void Restore (PackageRestorer restorer, Action afterRestore)
+ {
ProgressMonitorStatusMessage progressMessage = ProgressMonitorStatusMessageFactory.CreateRestoringPackagesBeforeUpdateMessage ();
- var restorer = new PackageRestorer (projects);
DispatchService.BackgroundDispatch (() => {
restorer.Restore (progressMessage);
if (!restorer.RestoreFailed) {
@@ -84,6 +90,12 @@ namespace MonoDevelop.PackageManagement }
});
}
+
+ public void RestoreProjectPackages (DotNetProject project, Action afterRestore)
+ {
+ var restorer = new PackageRestorer (project);
+ Restore (restorer, afterRestore);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RestorePackagesAction.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RestorePackagesAction.cs new file mode 100644 index 0000000000..17e844d4da --- /dev/null +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RestorePackagesAction.cs @@ -0,0 +1,192 @@ +//
+// RestorePackagesAction.cs
+//
+// Author:
+// Matt Ward <matt.ward@xamarin.com>
+//
+// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using ICSharpCode.PackageManagement;
+using NuGet;
+using MonoDevelop.Core;
+
+namespace MonoDevelop.PackageManagement
+{
+ public class RestorePackagesAction : IPackageAction
+ {
+ IPackageManagementSolution solution;
+ ISolutionPackageRepository solutionPackageRepository;
+ IPackageRepositoryCache repositoryCache;
+ IPackageManagerFactory packageManagerFactory;
+ ILogger logger;
+
+ public RestorePackagesAction ()
+ : this (
+ PackageManagementServices.Solution,
+ PackageManagementServices.PackageManagementEvents)
+ {
+ }
+
+ public RestorePackagesAction (
+ IPackageManagementSolution solution,
+ IPackageManagementEvents packageManagementEvents)
+ : this (
+ solution,
+ packageManagementEvents,
+ PackageManagementServices.PackageRepositoryCache,
+ new SharpDevelopPackageManagerFactory ())
+ {
+ }
+
+ public RestorePackagesAction (
+ IPackageManagementSolution solution,
+ IPackageManagementEvents packageManagementEvents,
+ IPackageRepositoryCache repositoryCache,
+ IPackageManagerFactory packageManagerFactory)
+ {
+ this.solution = solution;
+ this.repositoryCache = repositoryCache;
+ this.packageManagerFactory = packageManagerFactory;
+
+ logger = new PackageManagementLogger (packageManagementEvents);
+ }
+
+ public IDotNetProject Project { get; set; }
+
+ public void Execute ()
+ {
+ Log ("Restoring packages...");
+
+ int packagesRestored = 0;
+ List<PackageReference> packageReferences = GetPackageReferences ().ToList ();
+ foreach (PackageReference packageReference in packageReferences) {
+ if (IsPackageRestored (packageReference)) {
+ LogPackageAlreadyRestored (packageReference);
+ } else {
+ packagesRestored++;
+ RestorePackage (packageReference.Id, packageReference.Version);
+ }
+ }
+
+ LogResult (packageReferences.Count, packagesRestored);
+ }
+
+ void Log (string message)
+ {
+ logger.Log (MessageLevel.Info, message);
+ }
+
+ void LogPackageAlreadyRestored (PackageReference packageReference)
+ {
+ logger.Log (MessageLevel.Debug, GettextCatalog.GetString ("Skipping '{0}' because it is already restored.", packageReference));
+ }
+
+ void LogResult (int totalPackageReferences, int packagesRestored)
+ {
+ if (packagesRestored == 0) {
+ Log ("All packages are already restored.");
+ } else if (packagesRestored == 1) {
+ Log (GettextCatalog.GetString ("1 package restored successfully."));
+ } else if (packagesRestored > 0) {
+ Log (GettextCatalog.GetString ("{0} packages restored successfully.", packagesRestored));
+ }
+ }
+
+ IEnumerable<PackageReference> GetPackageReferences ()
+ {
+ if (Project != null) {
+ return GetPackageReferencesForSingleProject ();
+ }
+ return GetPackageReferencesForSolution ()
+ .Concat (GetPackageReferencesForAllProjects ());
+ }
+
+ IEnumerable<PackageReference> GetPackageReferencesForSingleProject ()
+ {
+ IPackageRepository repository = repositoryCache.CreateAggregateRepository ();
+ IPackageManagementProject project = solution.GetProject (repository, Project);
+ return project.GetPackageReferences ();
+ }
+
+ IEnumerable<PackageReference> GetPackageReferencesForSolution ()
+ {
+ return SolutionPackageRepository.GetPackageReferences ();
+ }
+
+ IEnumerable<PackageReference> GetPackageReferencesForAllProjects ()
+ {
+ return solution
+ .GetProjects (repositoryCache.CreateAggregateRepository ())
+ .SelectMany (project => project.GetPackageReferences ())
+ .Distinct ();
+ }
+
+ bool IsPackageRestored (PackageReference packageReference)
+ {
+ return SolutionPackageRepository.IsRestored (packageReference);
+ }
+
+ ISolutionPackageRepository SolutionPackageRepository {
+ get {
+ if (solutionPackageRepository == null) {
+ solutionPackageRepository = solution.GetRepository ();
+ }
+ return solutionPackageRepository;
+ }
+ }
+
+ void RestorePackage (string packageId, SemanticVersion version)
+ {
+ IPackageRepository sourceRepository = CreateSourceRepository ();
+ using (IDisposable operation = sourceRepository.StartRestoreOperation (packageId, version.ToString ())) {
+ IPackage package = PackageHelper.ResolvePackage (sourceRepository, packageId, version);
+ IPackageManager packageManager = CreatePackageManager (sourceRepository);
+
+ packageManager.InstallPackage (
+ package,
+ ignoreDependencies: true,
+ allowPrereleaseVersions: true,
+ ignoreWalkInfo: true);
+ }
+ }
+
+ IPackageRepository CreateSourceRepository ()
+ {
+ return repositoryCache.CreateAggregateWithPriorityMachineCacheRepository ();
+ }
+
+ IPackageManager CreatePackageManager (IPackageRepository sourceRepository)
+ {
+ IPackageManager packageManager = packageManagerFactory.CreatePackageManager (sourceRepository, SolutionPackageRepository);
+ packageManager.Logger = logger;
+ return packageManager;
+ }
+
+ public bool HasPackageScriptsToRun ()
+ {
+ return false;
+ }
+ }
+}
+
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SettingsProvider.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SettingsProvider.cs index 8d277b8f69..2488c558da 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SettingsProvider.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SettingsProvider.cs @@ -28,6 +28,7 @@ using System; using System.IO;
using ICSharpCode.PackageManagement;
using NuGet;
+using MonoDevelop.Core;
namespace MonoDevelop.PackageManagement
{
@@ -62,7 +63,12 @@ namespace MonoDevelop.PackageManagement public ISettings LoadSettings ()
{
- return LoadSettings (GetSolutionDirectory ());
+ try {
+ return LoadSettings (GetSolutionDirectory ());
+ } catch (Exception ex) {
+ LoggingService.LogInternalError ("Unable to load NuGet.Config file.", ex);
+ }
+ return NullSettings.Instance;
}
string GetSolutionDirectory ()
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageManagerFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageManagerFactory.cs index b73f1a0b20..02626127aa 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageManagerFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageManagerFactory.cs @@ -80,5 +80,16 @@ namespace ICSharpCode.PackageManagement {
return projectSystemFactory.CreateProjectSystem(project);
}
+
+ public IPackageManager CreatePackageManager (
+ IPackageRepository sourceRepository,
+ ISolutionPackageRepository solutionPackageRepository)
+ {
+ return new PackageManager (
+ sourceRepository,
+ solutionPackageRepository.PackagePathResolver,
+ solutionPackageRepository.FileSystem,
+ solutionPackageRepository.Repository);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageRepositoryFactory.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageRepositoryFactory.cs index 938cf529a5..afcd7dffb4 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageRepositoryFactory.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SharpDevelopPackageRepositoryFactory.cs @@ -28,6 +28,7 @@ using System;
using System.Collections.Generic;
+using MonoDevelop.PackageManagement;
using NuGet;
namespace ICSharpCode.PackageManagement
@@ -51,7 +52,7 @@ namespace ICSharpCode.PackageManagement public IPackageRepository CreateAggregateRepository(IEnumerable<IPackageRepository> repositories)
{
- return new AggregateRepository(repositories);
+ return new MonoDevelopAggregateRepository (repositories);
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionExtensions.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionExtensions.cs index c77db7ebe2..2ed0ee5e66 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionExtensions.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionExtensions.cs @@ -29,7 +29,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
-using MonoDevelop.Core.ProgressMonitoring;
+using MonoDevelop.Core;
using MonoDevelop.Projects;
namespace ICSharpCode.PackageManagement
@@ -38,7 +38,7 @@ namespace ICSharpCode.PackageManagement {
public static void Save(this Solution solution)
{
- solution.Save(new NullProgressMonitor());
+ solution.Save(new ProgressMonitor());
}
public static IEnumerable<DotNetProject> GetAllDotNetProjects (this Solution solution)
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionPackageRepository.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionPackageRepository.cs index 47600b40a3..da361f1f20 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionPackageRepository.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/SolutionPackageRepository.cs @@ -115,5 +115,30 @@ namespace ICSharpCode.PackageManagement {
return repository.GetPackages();
}
+
+ public bool IsRestored (PackageReference packageReference)
+ {
+ if (packageReference.Version == null) {
+ return false;
+ }
+
+ return CreateLocalPackageRepository ()
+ .GetPackageLookupPaths (packageReference.Id, packageReference.Version)
+ .Any ();
+ }
+
+ protected virtual LocalPackageRepository CreateLocalPackageRepository ()
+ {
+ return new LocalPackageRepository (packagePathResolver, fileSystem);
+ }
+
+ public IEnumerable<PackageReference> GetPackageReferences ()
+ {
+ var sharedRepository = Repository as SharedPackageRepository;
+ if (sharedRepository != null) {
+ return sharedRepository.PackageReferenceFile.GetPackageReferences ();
+ }
+ return Enumerable.Empty <PackageReference> ();
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ThreadSafePackageManagementEvents.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ThreadSafePackageManagementEvents.cs index 394a4089a3..f4a3eaf390 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ThreadSafePackageManagementEvents.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/ThreadSafePackageManagementEvents.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using MonoDevelop.Core;
using MonoDevelop.Ide;
using NuGet;
+using MonoDevelop.PackageManagement;
namespace ICSharpCode.PackageManagement
{
@@ -272,5 +273,15 @@ namespace ICSharpCode.PackageManagement {
unsafeEvents.OnUpdatedPackagesAvailable ();
}
+
+ public event EventHandler<FileRemovingEventArgs> FileRemoving {
+ add { unsafeEvents.FileRemoving += value; }
+ remove { unsafeEvents.FileRemoving -= value; }
+ }
+
+ public bool OnFileRemoving (string path)
+ {
+ return unsafeEvents.OnFileRemoving (path);
+ }
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatePackageAction.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatePackageAction.cs index 5ece2f0a90..888c0a861e 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatePackageAction.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatePackageAction.cs @@ -29,16 +29,33 @@ using System;
using System.Collections.Generic;
using NuGet;
+using MonoDevelop.PackageManagement;
namespace ICSharpCode.PackageManagement
{
public class UpdatePackageAction : ProcessPackageOperationsAction, IUpdatePackageSettings
{
- public UpdatePackageAction(
+ IPackageManagementEvents packageManagementEvents;
+ IFileRemover fileRemover;
+
+ public UpdatePackageAction (
IPackageManagementProject project,
IPackageManagementEvents packageManagementEvents)
- : base(project, packageManagementEvents)
+ : this (
+ project,
+ packageManagementEvents,
+ new FileRemover ())
+ {
+ }
+
+ public UpdatePackageAction (
+ IPackageManagementProject project,
+ IPackageManagementEvents packageManagementEvents,
+ IFileRemover fileRemover)
+ : base (project, packageManagementEvents)
{
+ this.packageManagementEvents = packageManagementEvents;
+ this.fileRemover = fileRemover;
UpdateDependencies = true;
UpdateIfPackageDoesNotExistInProject = true;
}
@@ -57,7 +74,9 @@ namespace ICSharpCode.PackageManagement protected override void ExecuteCore()
{
if (ShouldUpdatePackage()) {
- Project.UpdatePackage(Package, this);
+ using (IDisposable monitor = CreateFileMonitor ()) {
+ Project.UpdatePackage(Package, this);
+ }
OnParentPackageInstalled();
}
}
@@ -70,6 +89,13 @@ namespace ICSharpCode.PackageManagement return true;
}
+ IDisposable CreateFileMonitor ()
+ {
+ return new PreventPackagesConfigFileBeingRemovedOnUpdateMonitor (
+ packageManagementEvents,
+ fileRemover);
+ }
+
protected override string StartingMessageFormat {
get { return "Updating {0}..."; }
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackages.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackages.cs index 7e01c69ed0..3d2984e654 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackages.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackages.cs @@ -38,19 +38,22 @@ namespace ICSharpCode.PackageManagement {
IPackageRepository sourceRepository;
List<IPackageName> installedPackages;
+ IPackageConstraintProvider constraintProvider;
public UpdatedPackages (
IPackageManagementProject project,
IPackageRepository aggregateRepository)
: this (
project.GetPackageReferences (),
- aggregateRepository)
+ aggregateRepository,
+ project.ConstraintProvider)
{
}
public UpdatedPackages (
IEnumerable<PackageReference> packageReferences,
- IPackageRepository aggregrateRepository)
+ IPackageRepository aggregrateRepository,
+ IPackageConstraintProvider constraintProvider)
{
installedPackages = packageReferences
.Select (packageReference => new PackageName (packageReference.Id, packageReference.Version))
@@ -58,6 +61,7 @@ namespace ICSharpCode.PackageManagement .ToList ();
this.sourceRepository = aggregrateRepository;
+ this.constraintProvider = constraintProvider;
}
public UpdatedPackages(
@@ -71,14 +75,14 @@ namespace ICSharpCode.PackageManagement public IEnumerable<IPackage> GetUpdatedPackages (bool includePrerelease = false)
{
List<IPackageName> localPackages = installedPackages;
- IEnumerable<IPackageName> distinctLocalPackages = DistinctPackages2 (localPackages);
- return GetUpdatedPackages (sourceRepository, distinctLocalPackages, includePrerelease);
+ IEnumerable<IPackageName> distinctLocalPackages = DistinctPackages (localPackages);
+ return GetUpdatedPackages (distinctLocalPackages, includePrerelease);
}
/// <summary>
/// If we have jQuery 1.6 and 1.7 then return just jquery 1.6
/// </summary>
- IEnumerable<IPackageName> DistinctPackages2 (List<IPackageName> packages)
+ IEnumerable<IPackageName> DistinctPackages (List<IPackageName> packages)
{
if (packages.Any ()) {
packages.Sort ((x, y) => x.Version.CompareTo (y.Version));
@@ -88,11 +92,18 @@ namespace ICSharpCode.PackageManagement }
IEnumerable<IPackage> GetUpdatedPackages (
- IPackageRepository sourceRepository,
IEnumerable<IPackageName> localPackages,
bool includePrelease)
{
- return sourceRepository.GetUpdates (localPackages, includePrelease, false);
+ IEnumerable<IVersionSpec> constraints = localPackages
+ .Select (package => constraintProvider.GetConstraint (package.Id));
+
+ return sourceRepository.GetUpdates (
+ localPackages,
+ includePrelease,
+ false,
+ null,
+ constraints);
}
}
}
diff --git a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackagesInSolution.cs b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackagesInSolution.cs index 1ed3238092..696a33cde0 100644 --- a/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackagesInSolution.cs +++ b/main/src/addins/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/UpdatedPackagesInSolution.cs @@ -111,6 +111,7 @@ namespace MonoDevelop.PackageManagement {
LogCheckingForUpdates (project.Name);
+ project.Logger = new PackageManagementLogger (packageManagementEvents);
var updatedPackages = new UpdatedPackages (project, project.SourceRepository);
List<IPackage> packages = updatedPackages.GetUpdatedPackages ().ToList ();
diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/AnalysisCommands.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/AnalysisCommands.cs index 4fe2c5f86f..392aacd522 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/AnalysisCommands.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/AnalysisCommands.cs @@ -59,10 +59,18 @@ namespace MonoDevelop.AnalysisCore { protected override void Update (CommandInfo info) { - MonoDevelop.Ide.Gui.Document document; - IList<FixableResult> results; - info.Enabled = FixOperationsHandler.GetFixes (out document, out results) - && results.Any (r => FixOperationsHandler.GetActions (document, r).Any ()); + var doc = MonoDevelop.Ide.IdeApp.Workbench.ActiveDocument; + if (doc == null || doc.Editor == null) { + info.Enabled = false; + return; + } + var codeActionExtension = doc.GetContent <CodeActionEditorExtension> (); + if (codeActionExtension == null) { + info.Enabled = false; + return; + } + var fixes = codeActionExtension.GetCurrentFixes (); + info.Enabled = fixes.Any (); } protected override void Run () diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionEditorExtension.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionEditorExtension.cs index 9c3b135e75..ea74e0f17b 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionEditorExtension.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionEditorExtension.cs @@ -607,12 +607,12 @@ namespace MonoDevelop.CodeActions currentSmartTag.Popup (); } + static readonly List<CodeAction> emptyList = new List<CodeAction> (); internal List<CodeAction> GetCurrentFixes () { - if (currentSmartTag == null) + if (QuickTaskStrip.EnableFancyFeatures && currentSmartTag == null) return RefactoringService.GetValidActions (document, document.Editor.Caret.Location).Result.ToList (); - return currentSmartTag.fixes; + return currentSmartTag == null ? emptyList : currentSmartTag.fixes; } } -} - +}
\ No newline at end of file diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/BatchFixer.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/BatchFixer.cs index 783b45ff03..a0d4cf4cde 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/BatchFixer.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/BatchFixer.cs @@ -46,9 +46,9 @@ namespace MonoDevelop.CodeIssues { readonly IActionMatcher matcher; - readonly IProgressMonitor monitor; + readonly ProgressMonitor monitor; - public BatchFixer (IActionMatcher matcher, IProgressMonitor monitor) + public BatchFixer (IActionMatcher matcher, ProgressMonitor monitor) { this.matcher = matcher; this.monitor = monitor; diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/Runner/ProgressMonitorWrapperJob.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/Runner/ProgressMonitorWrapperJob.cs index 6557a3c04e..b1eea307cf 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/Runner/ProgressMonitorWrapperJob.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/Runner/ProgressMonitorWrapperJob.cs @@ -36,7 +36,7 @@ namespace MonoDevelop.CodeIssues { readonly IAnalysisJob wrappedJob; - IProgressMonitor monitor;
+ ProgressMonitor monitor;
int reportingThinningFactor = 100;
diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameItemDialog.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameItemDialog.cs index c39249dc12..cb6bf8acef 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameItemDialog.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameItemDialog.cs @@ -113,6 +113,10 @@ namespace MonoDevelop.Refactoring.Rename entry.Text = member.Name; } // fileName = member.Region.FileName; + } else if (options.SelectedItem is IType) { + var lvar = (IType)options.SelectedItem; + entry.Text = lvar.Name; + // this.fileName = lvar.Region.FileName; } else if (options.SelectedItem is ITypeParameter) { var lvar = (ITypeParameter)options.SelectedItem; entry.Text = lvar.Name; @@ -183,7 +187,7 @@ namespace MonoDevelop.Refactoring.Rename var properties = Properties; ((Widget)this).Destroy (); List<Change> changes = rename.PerformChanges (options, properties); - IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (this.Title, null); + ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (this.Title, null); RefactoringService.AcceptChanges (monitor, changes); } diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameRefactoring.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameRefactoring.cs index 7a3cf5a6c3..2faf66fb59 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameRefactoring.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.Rename/RenameRefactoring.cs @@ -89,7 +89,7 @@ namespace MonoDevelop.Refactoring.Rename new RenameRefactoring ().Run (options); return; } - using (var monitor = new NullProgressMonitor ()) { + using (var monitor = new ProgressMonitor ()) { var col = ReferenceFinder.FindReferences (entity, true, monitor); List<Change> result = new List<Change> (); @@ -110,7 +110,7 @@ namespace MonoDevelop.Refactoring.Rename public static void RenameVariable (IVariable variable, string newName) { - using (var monitor = new NullProgressMonitor ()) { + using (var monitor = new ProgressMonitor ()) { var col = ReferenceFinder.FindReferences (variable, true, monitor); List<Change> result = new List<Change> (); @@ -139,7 +139,7 @@ namespace MonoDevelop.Refactoring.Rename return; } - using (var monitor = new NullProgressMonitor ()) { + using (var monitor = new ProgressMonitor ()) { var col = ReferenceFinder.FindReferences (typeParameter, true, monitor); List<Change> result = new List<Change> (); @@ -160,7 +160,7 @@ namespace MonoDevelop.Refactoring.Rename public static void RenameNamespace (INamespace ns, string newName) { - using (var monitor = new NullProgressMonitor ()) { + using (var monitor = new ProgressMonitor ()) { var col = ReferenceFinder.FindReferences (ns, true, monitor); List<Change> result = new List<Change> (); diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/Change.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/Change.cs index 0f3805e639..3b09f630f7 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/Change.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/Change.cs @@ -47,7 +47,7 @@ namespace MonoDevelop.Refactoring { } - public abstract void PerformChange (IProgressMonitor monitor, RefactoringOptions rctx); + public abstract void PerformChange (ProgressMonitor monitor, RefactoringOptions rctx); } public class TextReplaceChange : Change @@ -118,7 +118,7 @@ namespace MonoDevelop.Refactoring return GetTextEditorData (FileName); } } - public override void PerformChange (IProgressMonitor monitor, RefactoringOptions rctx) + public override void PerformChange (ProgressMonitor monitor, RefactoringOptions rctx) { if (rctx == null) throw new InvalidOperationException ("Refactory context not available."); @@ -177,11 +177,11 @@ namespace MonoDevelop.Refactoring this.Description = string.Format (GettextCatalog.GetString ("Create file '{0}'"), Path.GetFileName (fileName)); } - public override void PerformChange (IProgressMonitor monitor, RefactoringOptions rctx) + public override void PerformChange (ProgressMonitor monitor, RefactoringOptions rctx) { File.WriteAllText (FileName, Content); rctx.Document.Project.AddFile (FileName); - IdeApp.ProjectOperations.Save (rctx.Document.Project); + IdeApp.ProjectOperations.SaveAsync (rctx.Document.Project); } } @@ -198,7 +198,7 @@ namespace MonoDevelop.Refactoring this.Description = string.Format (GettextCatalog.GetString ("Open file '{0}'"), Path.GetFileName (fileName)); } - public override void PerformChange (IProgressMonitor monitor, RefactoringOptions rctx) + public override void PerformChange (ProgressMonitor monitor, RefactoringOptions rctx) { IdeApp.Workbench.OpenDocument (FileName); } @@ -227,7 +227,7 @@ namespace MonoDevelop.Refactoring this.Description = string.Format (GettextCatalog.GetString ("Rename file '{0}' to '{1}'"), Path.GetFileName (oldName), Path.GetFileName (newName)); } - public override void PerformChange (IProgressMonitor monitor, RefactoringOptions rctx) + public override void PerformChange (ProgressMonitor monitor, RefactoringOptions rctx) { if (rctx == null) throw new ArgumentNullException ("rctx"); @@ -235,7 +235,7 @@ namespace MonoDevelop.Refactoring if (IdeApp.ProjectOperations.CurrentSelectedSolution != null) { foreach (var p in IdeApp.ProjectOperations.CurrentSelectedSolution.GetAllProjects ()) { if (p.GetProjectFile (NewName) != null) - IdeApp.ProjectOperations.Save (p); + IdeApp.ProjectOperations.SaveAsync (p); } } } @@ -254,9 +254,9 @@ namespace MonoDevelop.Refactoring this.Description = string.Format (GettextCatalog.GetString ("Save project {0}"), project.Name); } - public override void PerformChange (IProgressMonitor monitor, RefactoringOptions rctx) + public override void PerformChange (ProgressMonitor monitor, RefactoringOptions rctx) { - IdeApp.ProjectOperations.Save (this.Project); + IdeApp.ProjectOperations.SaveAsync (this.Project); } } } diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringPreviewDialog.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringPreviewDialog.cs index ecfbf2e593..0f98ee8010 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringPreviewDialog.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringPreviewDialog.cs @@ -87,7 +87,7 @@ namespace MonoDevelop.Refactoring }; buttonOk.Clicked += delegate { - IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (this.Title, null); + ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBackgroundProgressMonitor (this.Title, null); RefactoringService.AcceptChanges (monitor, changes); Destroy (); diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringService.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringService.cs index d91b6f9a6d..1d9353ba5e 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringService.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoringService.cs @@ -156,12 +156,12 @@ namespace MonoDevelop.Refactoring } } - public static void AcceptChanges (IProgressMonitor monitor, List<Change> changes) + public static void AcceptChanges (ProgressMonitor monitor, List<Change> changes) { AcceptChanges (monitor, changes, MonoDevelop.Ide.TextFileProvider.Instance); } - public static void AcceptChanges (IProgressMonitor monitor, List<Change> changes, MonoDevelop.Projects.Text.ITextFileProvider fileProvider) + public static void AcceptChanges (ProgressMonitor monitor, List<Change> changes, MonoDevelop.Projects.Text.ITextFileProvider fileProvider) { var rctx = new RefactoringOptions (null); var handler = new RenameHandler (changes); @@ -199,6 +199,9 @@ namespace MonoDevelop.Refactoring return inspectors.Where (i => i.MimeType == mimeType); } + static Stopwatch validActionsWatch = new Stopwatch (); + static Stopwatch actionWatch = new Stopwatch (); + public static Task<IEnumerable<CodeAction>> GetValidActions (Document doc, TextLocation loc, CancellationToken cancellationToken = default (CancellationToken)) { var editor = doc.Editor; @@ -207,6 +210,8 @@ namespace MonoDevelop.Refactoring var result = new List<CodeAction> (); var timer = InstrumentationService.CreateTimerCounter ("Source analysis background task", "Source analysis"); timer.BeginTiming (); + validActionsWatch.Restart (); + var timeTable = new Dictionary<CodeActionProvider, long> (); try { var parsedDocument = doc.ParsedDocument; if (editor != null && parsedDocument != null && parsedDocument.CreateRefactoringContext != null) { @@ -217,7 +222,10 @@ namespace MonoDevelop.Refactoring disabledNodes.IndexOf (fix.IdString, StringComparison.Ordinal) < 0)) { try { + actionWatch.Restart (); result.AddRange (provider.GetActions (doc, ctx, loc, cancellationToken)); + actionWatch.Stop (); + timeTable[provider] = actionWatch.ElapsedMilliseconds; } catch (Exception ex) { LoggingService.LogError ("Error in context action provider " + provider.Title, ex); } @@ -228,6 +236,14 @@ namespace MonoDevelop.Refactoring LoggingService.LogError ("Error in analysis service", ex); } finally { timer.EndTiming (); + validActionsWatch.Stop (); + if (validActionsWatch.ElapsedMilliseconds > 1000) { + LoggingService.LogWarning ("Warning slow edit action update."); + foreach (var pair in timeTable) { + if (pair.Value > 50) + LoggingService.LogInfo ("ACTION '" + pair.Key.Title + "' took " + pair.Value +"ms"); + } + } } return (IEnumerable<CodeAction>)result; }, cancellationToken); diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs index bb4555eb46..97ab500655 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs @@ -202,9 +202,12 @@ namespace MonoDevelop.Refactoring var unit = SyntaxTree.Parse (CreateStub (doc, offset), doc.FileName); + var parsedDocument = doc.ParsedDocument; + if (parsedDocument == null) + return null; return ResolveAtLocation.Resolve ( doc.Compilation, - doc.ParsedDocument.ParsedFile as CSharpUnresolvedFile, + parsedDocument.ParsedFile as CSharpUnresolvedFile, unit, location, out node); @@ -276,14 +279,14 @@ namespace MonoDevelop.Refactoring if (OnlyAddReference) return GettextCatalog.GetString ( "Reference '{0}'", - GetLibraryName ()); + GetLibraryName ().Replace ("_", "__")); if (Reference != null) return GettextCatalog.GetString ( "Reference '{0}' and use '{1}'", GetLibraryName (), - string.Format ("using {0};", Namespace)); + string.Format ("using {0};", Namespace.Replace ("_", "__"))); - return string.Format ("using {0};", Namespace); + return string.Format ("using {0};", Namespace.Replace ("_", "__")); } public string GetInsertNamespaceText (string member) @@ -291,10 +294,10 @@ namespace MonoDevelop.Refactoring if (Reference != null) return GettextCatalog.GetString ( "Reference '{0}' and use '{1}'", - GetLibraryName (), - Namespace + "." + member + GetLibraryName ().Replace ("_", "__"), + (Namespace + "." + member).Replace ("_", "__") ); - return Namespace + "." + member; + return (Namespace + "." + member).Replace ("_", "__"); } } @@ -338,14 +341,14 @@ namespace MonoDevelop.Refactoring var compilations = new List<Tuple<ICompilation, MonoDevelop.Projects.ProjectReference>> (); compilations.Add (Tuple.Create (doc.Compilation, (MonoDevelop.Projects.ProjectReference)null)); - var referencedItems = IdeApp.Workspace != null ? project.GetReferencedItems (IdeApp.Workspace.ActiveConfiguration).ToList () : (IEnumerable<SolutionItem>) new SolutionItem[0]; + var referencedItems = IdeApp.Workspace != null ? project.GetReferencedItems (IdeApp.Workspace.ActiveConfiguration).ToList () : (IEnumerable<SolutionFolderItem>) new SolutionFolderItem[0]; var solution = project != null ? project.ParentSolution : null; if (solution != null) { foreach (var curProject in solution.GetAllProjects ()) { if (curProject == project || referencedItems.Contains (curProject)) continue; - var otherRefes = IdeApp.Workspace != null ? curProject.GetReferencedItems (IdeApp.Workspace.ActiveConfiguration).ToList () : (IEnumerable<SolutionItem>) new SolutionItem[0]; + var otherRefes = IdeApp.Workspace != null ? curProject.GetReferencedItems (IdeApp.Workspace.ActiveConfiguration).ToList () : (IEnumerable<SolutionFolderItem>) new SolutionFolderItem[0]; if (otherRefes.Contains (project)) continue; @@ -540,7 +543,7 @@ namespace MonoDevelop.Refactoring if (reference != null) { var project = doc.Project; project.Items.Add (reference); - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); } if (string.IsNullOrEmpty (ns)) diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/BehaviorPanel.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/BehaviorPanel.cs index e916b46e87..ccf1be8f63 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/BehaviorPanel.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/BehaviorPanel.cs @@ -40,9 +40,8 @@ namespace MonoDevelop.SourceEditor.OptionPanels indentationCombobox.InsertText (2, GettextCatalog.GetString ("Smart")); // indentationCombobox.InsertText (3, GettextCatalog.GetString ("Virtual")); - controlLeftRightCombobox.InsertText (0, GettextCatalog.GetString ("MonoDevelop")); - controlLeftRightCombobox.InsertText (1, GettextCatalog.GetString ("Emacs")); - controlLeftRightCombobox.InsertText (2, GettextCatalog.GetString ("SharpDevelop")); + controlLeftRightCombobox.InsertText (0, GettextCatalog.GetString ("Unix")); + controlLeftRightCombobox.InsertText (1, GettextCatalog.GetString ("Windows")); autoInsertBraceCheckbutton.Toggled += HandleAutoInsertBraceCheckbuttonToggled; } @@ -55,7 +54,7 @@ namespace MonoDevelop.SourceEditor.OptionPanels tabAsReindentCheckbutton.Active = DefaultSourceEditorOptions.Instance.TabIsReindent; indentationCombobox.Active = (int)DefaultSourceEditorOptions.Instance.IndentStyle; - controlLeftRightCombobox.Active = (int)DefaultSourceEditorOptions.Instance.ControlLeftRightMode; + controlLeftRightCombobox.Active = (int)DefaultSourceEditorOptions.Instance.WordNavigationStyle; useViModesCheck.Active = DefaultSourceEditorOptions.Instance.UseViModes; checkbuttonOnTheFlyFormatting.Active = DefaultSourceEditorOptions.Instance.OnTheFlyFormatting; checkbuttonGenerateFormattingUndoStep.Active = DefaultSourceEditorOptions.Instance.GenerateFormattingUndoStep; @@ -79,7 +78,7 @@ namespace MonoDevelop.SourceEditor.OptionPanels DefaultSourceEditorOptions.Instance.SmartSemicolonPlacement = smartSemicolonPlaceCheckbutton.Active; DefaultSourceEditorOptions.Instance.IndentStyle = (IndentStyle)indentationCombobox.Active; DefaultSourceEditorOptions.Instance.TabIsReindent = tabAsReindentCheckbutton.Active; - DefaultSourceEditorOptions.Instance.ControlLeftRightMode = (ControlLeftRightMode)controlLeftRightCombobox.Active; + DefaultSourceEditorOptions.Instance.WordNavigationStyle = (WordNavigationStyle)controlLeftRightCombobox.Active; DefaultSourceEditorOptions.Instance.UseViModes = useViModesCheck.Active; DefaultSourceEditorOptions.Instance.OnTheFlyFormatting = checkbuttonOnTheFlyFormatting.Active; DefaultSourceEditorOptions.Instance.GenerateFormattingUndoStep = checkbuttonGenerateFormattingUndoStep.Active; diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs index 102de5bf0a..a88335d795 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs @@ -71,7 +71,8 @@ namespace MonoDevelop.SourceEditor void HandleTextEditorDataSelectionChanged (object sender, EventArgs e) { - RemoveMarkers (); + if (TextEditorData.IsSomethingSelected) + RemoveMarkers (); } void HandleTextEditorDataDocumentTextReplaced (object sender, DocumentChangeEventArgs e) diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs index dadd156bd5..1f09e62575 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs @@ -40,11 +40,11 @@ namespace MonoDevelop.SourceEditor { public class ErrorText { - public Task Task { get; set; } + public UserTask Task { get; set; } public bool IsError { get; set; } public string ErrorMessage { get; set; } - public ErrorText (Task task, bool isError, string errorMessage) + public ErrorText (UserTask task, bool isError, string errorMessage) { this.Task = task; this.IsError = isError; diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs index 7484634970..c80f55b283 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs @@ -61,7 +61,7 @@ namespace MonoDevelop.SourceEditor get { return errors; } } - Task task; + UserTask task; DocumentLine lineSegment; // int editorAllocHeight = -1; // int lastLineLength = -1; @@ -143,7 +143,7 @@ namespace MonoDevelop.SourceEditor string initialText; bool isError; - internal MessageBubbleTextMarker (MessageBubbleCache cache, Task task, DocumentLine lineSegment, bool isError, string errorMessage) + internal MessageBubbleTextMarker (MessageBubbleCache cache, UserTask task, DocumentLine lineSegment, bool isError, string errorMessage) { if (cache == null) throw new ArgumentNullException ("cache"); @@ -158,7 +158,7 @@ namespace MonoDevelop.SourceEditor } static System.Text.RegularExpressions.Regex mcsErrorFormat = new System.Text.RegularExpressions.Regex ("(.+)\\(CS\\d+\\)\\Z"); - public void AddError (Task task, bool isError, string errorMessage) + public void AddError (UserTask task, bool isError, string errorMessage) { var match = mcsErrorFormat.Match (errorMessage); if (match.Success) diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorOptions.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorOptions.cs index 1aff7ad2ae..349021bdef 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorOptions.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorOptions.cs @@ -33,11 +33,18 @@ using MonoDevelop.Ide.Fonts; namespace MonoDevelop.SourceEditor { - public enum ControlLeftRightMode { + [Obsolete ("Use WordNavigationStyle")] + public enum ControlLeftRightMode + { MonoDevelop, Emacs, SharpDevelop - + } + + public enum WordNavigationStyle + { + Unix, + Windows } public enum LineEndingConversion { @@ -180,8 +187,8 @@ namespace MonoDevelop.SourceEditor case "OnTheFlyFormatting": this.OnTheFlyFormatting = (bool)args.NewValue; break; - case "ControlLeftRightMode": - this.ControlLeftRightMode = (ControlLeftRightMode)args.NewValue; + case "WordNavigationStyle": + this.WordNavigationStyle = (WordNavigationStyle)args.NewValue; break; case "EnableAnimations": base.EnableAnimations = (bool)args.NewValue; @@ -223,8 +230,13 @@ namespace MonoDevelop.SourceEditor this.defaultCommentFolding = PropertyService.Get ("DefaultCommentFolding", true); this.useViModes = PropertyService.Get ("UseViModes", false); this.onTheFlyFormatting = PropertyService.Get ("OnTheFlyFormatting", true); - var defaultControlMode = (ControlLeftRightMode)Enum.Parse (typeof(ControlLeftRightMode), DesktopService.DefaultControlLeftRightBehavior); - this.ControlLeftRightMode = PropertyService.Get ("ControlLeftRightMode", defaultControlMode); + + WordNavigationStyle defaultWordNavigation = WordNavigationStyle.Unix; + if (Platform.IsWindows || PropertyService.Get ("ControlLeftRightMode", (string)null) == "SharpDevelop") { + defaultWordNavigation = WordNavigationStyle.Windows; + } + this.WordNavigationStyle = PropertyService.Get ("WordNavigationStyle", defaultWordNavigation); + base.EnableAnimations = PropertyService.Get ("EnableAnimations", true); this.EnableHighlightUsages = PropertyService.Get ("EnableHighlightUsages", false); base.DrawIndentationMarkers = PropertyService.Get ("DrawIndentationMarkers", false); @@ -448,18 +460,38 @@ namespace MonoDevelop.SourceEditor get { return defaultEolMarker; } } - ControlLeftRightMode controlLeftRightMode = Platform.IsWindows - ? ControlLeftRightMode.SharpDevelop - : ControlLeftRightMode.MonoDevelop; - + WordNavigationStyle wordNavigationStyle = Platform.IsWindows + ? WordNavigationStyle.Windows + : WordNavigationStyle.Unix; + + [Obsolete("Use WordNavigationStyle")] public ControlLeftRightMode ControlLeftRightMode { get { - return controlLeftRightMode; + return WordNavigationStyle == WordNavigationStyle.Unix + ? ControlLeftRightMode.MonoDevelop + : ControlLeftRightMode.SharpDevelop; } set { - if (controlLeftRightMode != value) { - controlLeftRightMode = value; - PropertyService.Set ("ControlLeftRightMode", value); + switch (value) { + case ControlLeftRightMode.Emacs: + case ControlLeftRightMode.MonoDevelop: + WordNavigationStyle = WordNavigationStyle.Unix; + return; + default: + WordNavigationStyle = WordNavigationStyle.Windows; + return; + } + } + } + + public WordNavigationStyle WordNavigationStyle { + get { + return wordNavigationStyle; + } + set { + if (wordNavigationStyle != value) { + wordNavigationStyle = value; + PropertyService.Set ("WordNavigationStyle", value); SetWordFindStrategy (); OnChanged (EventArgs.Empty); } @@ -481,19 +513,16 @@ namespace MonoDevelop.SourceEditor void SetWordFindStrategy () { if (useViModes) { - this.wordFindStrategy = new Mono.TextEditor.Vi.ViWordFindStrategy (); + wordFindStrategy = new Mono.TextEditor.Vi.ViWordFindStrategy (); return; } - switch (ControlLeftRightMode) { - case ControlLeftRightMode.MonoDevelop: - this.wordFindStrategy = new EmacsWordFindStrategy (true); - break; - case ControlLeftRightMode.Emacs: - this.wordFindStrategy = new EmacsWordFindStrategy (false); + switch (WordNavigationStyle) { + case WordNavigationStyle.Windows: + wordFindStrategy = new SharpDevelopWordFindStrategy (); break; - case ControlLeftRightMode.SharpDevelop: - this.wordFindStrategy = new SharpDevelopWordFindStrategy (); + default: + wordFindStrategy = new EmacsWordFindStrategy (); break; } } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs index d301d929f5..97788a8b15 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs @@ -562,7 +562,7 @@ namespace MonoDevelop.SourceEditor void UpdateTasks (object sender, TaskEventArgs e) { - Task[] tasks = TaskService.Errors.GetFileTasks (ContentName); + UserTask[] tasks = TaskService.Errors.GetFileTasks (ContentName); if (tasks == null) return; DisposeErrorMarkers (); // disposes messageBubbleCache as well. @@ -573,7 +573,7 @@ namespace MonoDevelop.SourceEditor messageBubbleCache.Dispose (); messageBubbleCache = new MessageBubbleCache (widget.TextEditor); - foreach (Task task in tasks) { + foreach (UserTask task in tasks) { if (task.Severity == TaskSeverity.Error || task.Severity == TaskSeverity.Warning) { if (IdeApp.Preferences.ShowMessageBubbles == ShowMessageBubbles.ForErrors && task.Severity == TaskSeverity.Warning) continue; diff --git a/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Commands/WebReferenceCommandHandler.cs b/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Commands/WebReferenceCommandHandler.cs index 6a50df42ec..fcf9d390cf 100644 --- a/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Commands/WebReferenceCommandHandler.cs +++ b/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Commands/WebReferenceCommandHandler.cs @@ -47,7 +47,7 @@ namespace MonoDevelop.WebReferences.Commands return; dialog.SelectedService.GenerateFiles (project, dialog.Namespace, dialog.ReferenceName); - IdeApp.ProjectOperations.Save(project); + IdeApp.ProjectOperations.SaveAsync(project); } catch (Exception exception) { MessageService.ShowException (exception); } finally { @@ -105,7 +105,7 @@ namespace MonoDevelop.WebReferences.Commands DispatchService.GuiDispatch (() => { // Make sure that we save all relevant projects, there should only be 1 though foreach (var project in items.Select (i =>i.Project).Distinct ()) - IdeApp.ProjectOperations.Save (project); + IdeApp.ProjectOperations.SaveAsync (project); IdeApp.Workbench.StatusBar.ShowMessage(GettextCatalog.GetPluralString ("Updated Web Reference {0}", "Updated Web References", items.Count, items[0].Name)); DisposeUpdateContext (); @@ -133,7 +133,7 @@ namespace MonoDevelop.WebReferences.Commands if (!MessageService.Confirm (GettextCatalog.GetString ("Are you sure you want to delete the web service reference '{0}'?", item.Name), AlertButton.Delete)) return; item.Delete(); - IdeApp.ProjectOperations.Save (item.Project); + IdeApp.ProjectOperations.SaveAsync (item.Project); IdeApp.Workbench.StatusBar.ShowMessage("Deleted Web Reference " + item.Name); } @@ -153,7 +153,7 @@ namespace MonoDevelop.WebReferences.Commands foreach (var item in items.ToList ()) item.Delete(); - IdeApp.ProjectOperations.Save(project); + IdeApp.ProjectOperations.SaveAsync(project); IdeApp.Workbench.StatusBar.ShowMessage("Deleted all Web References"); } diff --git a/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WCFConfigWidget.cs b/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WCFConfigWidget.cs index d69ba80256..cfbea29412 100644 --- a/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WCFConfigWidget.cs +++ b/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WCFConfigWidget.cs @@ -53,7 +53,7 @@ namespace MonoDevelop.WebReferences.Dialogs listAccess.Active = options.GenerateInternalTypes ? 1 : 0; listAsync.Active = AsyncOptionToIndex; - if (project is PortableDotNetProject) { + if (project.IsPortableLibrary) { listAccess.Sensitive = false; listAsync.Sensitive = false; } diff --git a/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WebReferenceDialog.cs b/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WebReferenceDialog.cs index e5873989a4..9feda476cf 100644 --- a/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WebReferenceDialog.cs +++ b/main/src/addins/MonoDevelop.WebReferences/MonoDevelop.WebReferences.Dialogs/WebReferenceDialog.cs @@ -169,7 +169,7 @@ namespace MonoDevelop.WebReferences.Dialogs tbxReferenceURL.Text = homeUrl; wcfOptions = WebReferencesService.WcfEngine.DefaultClientOptions; - if (project is PortableDotNetProject) { + if (project.IsPortableLibrary) { wcfOptions.GenerateAsynchronousMethods = false; wcfOptions.GenerateEventBasedAsynchronousMethods = true; } @@ -491,7 +491,7 @@ namespace MonoDevelop.WebReferences.Dialogs btnOK.Sensitive = isWebService; tlbNavigate.Visible = WebBrowserService.CanGetWebBrowser; tbxReferenceName.Sensitive = isWebService; - comboModel.Sensitive = !(project is PortableDotNetProject); + comboModel.Sensitive = !project.IsPortableLibrary; break; case DialogState.CreateConfig: diff --git a/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WCFConfigWidget.cs b/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WCFConfigWidget.cs index 26c8b48195..3788b1590a 100644 --- a/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WCFConfigWidget.cs +++ b/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WCFConfigWidget.cs @@ -5,14 +5,23 @@ namespace MonoDevelop.WebReferences.Dialogs public partial class WCFConfigWidget { private global::Gtk.VBox dialog1_VBox; + private global::Gtk.Table wcfOptions; + private global::Gtk.ComboBox dictionaryCollection; + private global::Gtk.Label label1; + private global::Gtk.Label label2; + private global::Gtk.Label label3; + private global::Gtk.Label label4; + private global::Gtk.ComboBox listAccess; + private global::Gtk.ComboBox listAsync; + private global::Gtk.ComboBox listCollection; protected virtual void Build () diff --git a/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WebReferenceDialog.cs b/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WebReferenceDialog.cs index 9a240c227b..b103b95f2a 100644 --- a/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WebReferenceDialog.cs +++ b/main/src/addins/MonoDevelop.WebReferences/gtk-gui/MonoDevelop.WebReferences.Dialogs.WebReferenceDialog.cs @@ -5,29 +5,53 @@ namespace MonoDevelop.WebReferences.Dialogs internal partial class WebReferenceDialog { private global::Gtk.UIManager UIManager; + private global::Gtk.Action btnNavBack; + private global::Gtk.Action btnNavNext; + private global::Gtk.Action btnRefresh; + private global::Gtk.Action btnStop; + private global::Gtk.Action btnHome; + private global::Gtk.VBox vbxContainer; + private global::Gtk.Toolbar tlbNavigate; + private global::Gtk.Table tblWebReferenceUrl; + private global::Gtk.Button btnGO; + private global::Gtk.Label lblWebServiceUrl; + private global::Gtk.Entry tbxReferenceURL; + private global::Gtk.Frame frmBrowser; + private global::Gtk.Table tblReferenceName; + private global::Gtk.HBox hbox1; + private global::Gtk.ComboBox comboModel; + private global::Gtk.Label label1; + private global::Gtk.Label lblNamespace; + private global::Gtk.Label lblReference; + private global::Gtk.Entry tbxNamespace; + private global::Gtk.Entry tbxReferenceName; + private global::Gtk.Button btnCancel; + private global::Gtk.Button btnBack; + private global::Gtk.Button btnOK; + private global::Gtk.Button btnConfig; protected virtual void Build () @@ -61,7 +85,7 @@ namespace MonoDevelop.WebReferences.Dialogs this.vbxContainer = new global::Gtk.VBox (); this.vbxContainer.Name = "vbxContainer"; // Container child vbxContainer.Gtk.Box+BoxChild - this.UIManager.AddUiFromString (@"<ui><toolbar name='tlbNavigate'><toolitem name='btnNavBack' action='btnNavBack'/><toolitem name='btnNavNext' action='btnNavNext'/><toolitem name='btnRefresh' action='btnRefresh'/><toolitem name='btnStop' action='btnStop'/><toolitem name='btnHome' action='btnHome'/></toolbar></ui>"); + this.UIManager.AddUiFromString ("<ui><toolbar name='tlbNavigate'><toolitem name='btnNavBack' action='btnNavBack'/><toolitem name='btnNavNext' action='btnNavNext'/><toolitem name='btnRefresh' action='btnRefresh'/><toolitem name='btnStop' action='btnStop'/><toolitem name='btnHome' action='btnHome'/></toolbar></ui>"); this.tlbNavigate = ((global::Gtk.Toolbar)(this.UIManager.GetWidget ("/tlbNavigate"))); this.tlbNavigate.Name = "tlbNavigate"; this.tlbNavigate.ShowArrow = false; diff --git a/main/src/addins/MonoDeveloperExtensions/Commands.cs b/main/src/addins/MonoDeveloperExtensions/Commands.cs index 9c0477378e..8cab36b704 100644 --- a/main/src/addins/MonoDeveloperExtensions/Commands.cs +++ b/main/src/addins/MonoDeveloperExtensions/Commands.cs @@ -50,13 +50,13 @@ namespace MonoDeveloper protected override void Update (CommandInfo info) { - info.Visible = MonoMakefileFormat.IsMonoProject (IdeApp.ProjectOperations.CurrentSelectedProject); + info.Visible = IdeApp.ProjectOperations.CurrentSelectedItem is MakefileProject; } void Install (object prj) { DotNetProject p = prj as DotNetProject; - using (IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor ()) { + using (ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor ()) { p.RunTarget (monitor, "install", IdeApp.Workspace.ActiveConfiguration); } } diff --git a/main/src/addins/MonoDeveloperExtensions/MakefileProject.cs b/main/src/addins/MonoDeveloperExtensions/MakefileProject.cs new file mode 100644 index 0000000000..d48001bfad --- /dev/null +++ b/main/src/addins/MonoDeveloperExtensions/MakefileProject.cs @@ -0,0 +1,405 @@ +// +// MakefileProject.cs +// +// Author: +// Lluis Sanchez Gual <lluis@xamarin.com> +// +// Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using MonoDevelop.Projects; +using MonoDevelop.Core; +using System.Collections; +using System.Threading.Tasks; +using System.IO; +using System.Text.RegularExpressions; +using MonoDevelop.Ide; +using MonoDevelop.Core.ProgressMonitoring; +using MonoDevelop.Core.Execution; +using System.CodeDom.Compiler; + +namespace MonoDeveloper +{ + public class MakefileProject: WorkspaceObject + { + string name; + FilePath file; + + public MakefileProject (string lang) + { + } + + public new string Name { + get { return name; } + set { name = value; } + } + + public FilePath FileName { + get { return file; } + set { file = value; } + } + + #region implemented abstract members of WorkspaceObject + + protected override string OnGetName () + { + return name; + } + + protected override string OnGetItemDirectory () + { + return file.ParentDirectory; + } + + protected override string OnGetBaseDirectory () + { + return file.ParentDirectory; + } + + #endregion + + + DotNetProject project; + string outFile; + ArrayList refNames = new ArrayList (); + bool loading; + string testFileBase; + object unitTest; + + public MakefileProject (DotNetProject project) + { + this.project = project; + project.FileAddedToProject += OnFileAddedToProject; + project.FileRemovedFromProject += OnFileRemovedFromProject; + project.FileRenamedInProject += OnFileRenamedInProject; + } + + public string SourcesFile { + get { return outFile + ".sources"; } + } + + public bool SyncFileName { + get { return false; } + } + + public string ItemId { + get { + if (project.ParentSolution != null) + return project.ParentSolution.GetRelativeChildPath (project.FileName); + else + return project.Name; + } + } + + public Task Save (MonoDevelop.Core.ProgressMonitor monitor) + { + return Task.FromResult (0); + } + + internal void Read (MonoMakefile mkfile) + { + loading = true; + + string basePath = Path.GetDirectoryName (mkfile.FileName); + string aname; + + string targetAssembly = mkfile.GetVariable ("LIBRARY"); + if (targetAssembly == null) { + targetAssembly = mkfile.GetVariable ("PROGRAM"); + if (Path.GetDirectoryName (targetAssembly) == "") + targetAssembly = Path.Combine (basePath, targetAssembly); + aname = Path.GetFileName (targetAssembly); + } else { + aname = Path.GetFileName (targetAssembly); + string targetName = mkfile.GetVariable ("LIBRARY_NAME"); + if (targetName != null) targetAssembly = targetName; + targetAssembly = "$(topdir)/class/lib/$(PROFILE)/" + targetAssembly; + } + + outFile = Path.Combine (basePath, aname); + project.FileName = mkfile.FileName; + + ArrayList checkedFolders = new ArrayList (); + + // Parse projects + string sources = outFile + ".sources"; + StreamReader sr = new StreamReader (sources); + string line; + while ((line = sr.ReadLine ()) != null) { + line = line.Trim (' ','\t'); + if (line != "") { + string fname = Path.Combine (basePath, line); + project.Files.Add (new ProjectFile (fname)); + + string dir = Path.GetDirectoryName (fname); + if (!checkedFolders.Contains (dir)) { + checkedFolders.Add (dir); + fname = Path.Combine (dir, "ChangeLog"); + if (File.Exists (fname)) + project.Files.Add (new ProjectFile (fname, BuildAction.Content)); + } + } + } + + sr.Close (); + + // Project references + string refs = mkfile.GetVariable ("LIB_MCS_FLAGS"); + if (refs == null || refs == "") refs = mkfile.GetVariable ("LOCAL_MCS_FLAGS"); + + if (refs != null && refs != "") { + Regex var = new Regex(@"(.*?/r:(?<ref>.*?)(( |\t)|$).*?)*"); + Match match = var.Match (refs); + if (match.Success) { + foreach (Capture c in match.Groups["ref"].Captures) + refNames.Add (Path.GetFileNameWithoutExtension (c.Value)); + } + } + + int i = basePath.LastIndexOf ("/mcs/", basePath.Length - 2); + string topdir = basePath.Substring (0, i + 4); + targetAssembly = targetAssembly.Replace ("$(topdir)", topdir); + + if (mkfile.GetVariable ("NO_TEST") != "yes") { + string tname = Path.GetFileNameWithoutExtension (aname) + "_test_"; + testFileBase = Path.Combine (basePath, tname); + } + + foreach (string sconf in MonoMakefileFormat.Configurations) { + DotNetProjectConfiguration conf = new DotNetProjectConfiguration (sconf); + conf.CompilationParameters = project.LanguageBinding.CreateCompilationParameters (null); + conf.OutputDirectory = basePath; + conf.OutputAssembly = Path.GetFileName (targetAssembly); + project.Configurations.Add (conf); + } + + loading = false; + IdeApp.Workspace.SolutionLoaded += CombineOpened; + } + + public void CombineOpened (object sender, SolutionEventArgs args) + { + if (args.Solution == project.ParentSolution) { + foreach (string pref in refNames) { + Project p = project.ParentSolution.FindProjectByName (pref); + if (p != null) project.References.Add (new ProjectReference (p)); + } + } + } + + static Regex regexError = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*[\+]*))?\)(:|)\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)", + RegexOptions.Compiled | RegexOptions.ExplicitCapture); + + public Task<BuildResult> RunTarget (MonoDevelop.Core.ProgressMonitor monitor, string target, ConfigurationSelector configuration) + { + if (target == ProjectService.BuildTarget) + target = "all"; + else if (target == ProjectService.CleanTarget) + target = "clean"; + + DotNetProjectConfiguration conf = (DotNetProjectConfiguration) project.GetConfiguration (configuration); + + return Task<BuildResult>.Factory.StartNew (delegate { + using (var output = new StringWriter ()) { + using (var tw = new LogTextWriter ()) { + tw.ChainWriter (output); + tw.ChainWriter (monitor.Log); + + using (ProcessWrapper proc = Runtime.ProcessService.StartProcess ("make", "PROFILE=" + conf.Id + " " + target, conf.OutputDirectory, monitor.Log, tw, null)) + proc.WaitForOutput (); + + tw.UnchainWriter (output); + tw.UnchainWriter (monitor.Log); + + CompilerResults cr = new CompilerResults (null); + string[] lines = output.ToString ().Split ('\n'); + foreach (string line in lines) { + CompilerError err = CreateErrorFromString (line); + if (err != null) + cr.Errors.Add (err); + } + + return new BuildResult (cr, output.ToString ()); + } + } + }); + } + + private CompilerError CreateErrorFromString (string error_string) + { + // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this. + if (error_string.StartsWith ("WROTE SYMFILE") || + error_string.StartsWith ("make[") || + error_string.StartsWith ("OffsetTable") || + error_string.StartsWith ("Compilation succeeded") || + error_string.StartsWith ("Compilation failed")) + return null; + + CompilerError error = new CompilerError(); + + Match match=regexError.Match(error_string); + if (!match.Success) + return null; + + string level = match.Result("${level}"); + if (level == "warning") + error.IsWarning = true; + else if (level != "error") + return null; + + if (String.Empty != match.Result("${file}")) + error.FileName = Path.Combine (project.BaseDirectory, match.Result("${file}")); + if (String.Empty != match.Result("${line}")) + error.Line=Int32.Parse(match.Result("${line}")); + if (String.Empty != match.Result("${column}")) + error.Column = Int32.Parse(match.Result("${column}")); + error.ErrorNumber = match.Result ("${number}"); + error.ErrorText = match.Result ("${message}"); + return error; + } + + void OnFileAddedToProject (object s, ProjectFileEventArgs args) + { + if (loading) return; + + foreach (ProjectFileEventInfo e in args) { + if (e.ProjectFile.BuildAction != BuildAction.Compile) + continue; + AddSourceFile (e.ProjectFile.Name); + } + } + + void OnFileRemovedFromProject (object s, ProjectFileEventArgs args) + { + if (loading) return; + + foreach (ProjectFileEventInfo e in args) { + if (e.ProjectFile.BuildAction != BuildAction.Compile) + continue; + + RemoveSourceFile (e.ProjectFile.Name); + } + } + + void OnFileRenamedInProject (object s, ProjectFileRenamedEventArgs args) + { + if (loading) return; + + foreach (ProjectFileRenamedEventInfo e in args) { + if (e.ProjectFile.BuildAction != BuildAction.Compile) + continue; + + if (RemoveSourceFile (e.OldName)) + AddSourceFile (e.NewName); + } + } + + void AddSourceFile (string sourceFile) + { + StreamReader sr = null; + StreamWriter sw = null; + + try { + sr = new StreamReader (outFile + ".sources"); + sw = new StreamWriter (outFile + ".sources.new"); + + string newFile = project.GetRelativeChildPath (sourceFile); + if (newFile.StartsWith ("./")) newFile = newFile.Substring (2); + + string line; + while ((line = sr.ReadLine ()) != null) { + string file = line.Trim (' ','\t'); + if (newFile != null && (file == "" || string.Compare (file, newFile) > 0)) { + sw.WriteLine (newFile); + newFile = null; + } + sw.WriteLine (line); + } + if (newFile != null) + sw.WriteLine (newFile); + } finally { + if (sr != null) sr.Close (); + if (sw != null) sw.Close (); + } + File.Delete (outFile + ".sources"); + File.Move (outFile + ".sources.new", outFile + ".sources"); + } + + bool RemoveSourceFile (string sourceFile) + { + StreamReader sr = null; + StreamWriter sw = null; + bool found = false; + + try { + sr = new StreamReader (outFile + ".sources"); + sw = new StreamWriter (outFile + ".sources.new"); + + string oldFile = project.GetRelativeChildPath (sourceFile); + if (oldFile.StartsWith ("./")) oldFile = oldFile.Substring (2); + + string line; + while ((line = sr.ReadLine ()) != null) { + string file = line.Trim (' ','\t'); + if (oldFile != file) + sw.WriteLine (line); + else + found = true; + } + } finally { + if (sr != null) sr.Close (); + if (sw != null) sw.Close (); + } + if (found) { + File.Delete (outFile + ".sources"); + File.Move (outFile + ".sources.new", outFile + ".sources"); + } + return found; + } + + public void Dispose () + { + project.FileAddedToProject -= OnFileAddedToProject; + project.FileRemovedFromProject -= OnFileRemovedFromProject; + project.FileRenamedInProject -= OnFileRenamedInProject; + IdeApp.Workspace.SolutionLoaded -= CombineOpened; + } + + public void OnModified (string hint) + { + } + + public string GetTestFileBase () + { + return testFileBase; + } + + public object UnitTest { + get { return unitTest; } + set { unitTest = value; } + } + + public object GetService (Type t) + { + return null; + } + } +} + diff --git a/main/src/addins/MonoDeveloperExtensions/MonoDeveloperExtensions.csproj b/main/src/addins/MonoDeveloperExtensions/MonoDeveloperExtensions.csproj index a994b138b5..17c7f36e9b 100644 --- a/main/src/addins/MonoDeveloperExtensions/MonoDeveloperExtensions.csproj +++ b/main/src/addins/MonoDeveloperExtensions/MonoDeveloperExtensions.csproj @@ -79,6 +79,7 @@ <Compile Include="Commands.cs" /> <Compile Include="MonoSolutionItemHandler.cs" /> <Compile Include="AddinInfo.cs" /> + <Compile Include="MakefileProject.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="MonoDeveloperExtensions.addin.xml"> diff --git a/main/src/addins/MonoDeveloperExtensions/MonoMakefileFormat.cs b/main/src/addins/MonoDeveloperExtensions/MonoMakefileFormat.cs index ce6dd41f4a..45376b3d8b 100644 --- a/main/src/addins/MonoDeveloperExtensions/MonoMakefileFormat.cs +++ b/main/src/addins/MonoDeveloperExtensions/MonoMakefileFormat.cs @@ -35,6 +35,7 @@ using MonoDevelop.Core; using System.Text.RegularExpressions; using MonoDevelop.Projects; using MonoDevelop.Projects.Extensions; +using System.Threading.Tasks; namespace MonoDeveloper { @@ -70,121 +71,118 @@ namespace MonoDeveloper public bool CanWriteFile (object obj) { - return (obj is SolutionFolder) || IsMonoProject (obj); + return (obj is SolutionFolder) || (obj is MakefileProject); }
- public void WriteFile (FilePath file, object node, IProgressMonitor monitor) + public Task WriteFile (FilePath file, object node, ProgressMonitor monitor) { + return Task.FromResult (0); }
public List<FilePath> GetItemFiles (object obj) {
List<FilePath> col = new List<FilePath> (); - DotNetProject mp = obj as DotNetProject; + var mp = obj as MakefileProject; if (mp != null) { - MonoSolutionItemHandler handler = ProjectExtensionUtil.GetItemHandler (mp) as MonoSolutionItemHandler; - if (handler != null && File.Exists (handler.SourcesFile)) { + if (File.Exists (mp.SourcesFile)) { col.Add (mp.FileName); - col.Add (handler.SourcesFile); + col.Add (mp.SourcesFile); } } return col; }
- public object ReadFile (FilePath fileName, Type expectedType, IProgressMonitor monitor) + public Task<object> ReadFile (FilePath fileName, Type expectedType, ProgressMonitor monitor) { return ReadFile (fileName, false, monitor); }
- public object ReadFile (FilePath fileName, bool hasParentSolution, IProgressMonitor monitor) - {
- FilePath basePath = fileName.ParentDirectory; - MonoMakefile mkfile = new MonoMakefile (fileName); - string aname = mkfile.GetVariable ("LIBRARY"); - if (aname == null) aname = mkfile.GetVariable ("PROGRAM"); + public Task<object> ReadFile (FilePath fileName, bool hasParentSolution, ProgressMonitor monitor) + { + return Task<object>.Factory.StartNew (delegate { + FilePath basePath = fileName.ParentDirectory; + MonoMakefile mkfile = new MonoMakefile (fileName); + string aname = mkfile.GetVariable ("LIBRARY"); + if (aname == null) + aname = mkfile.GetVariable ("PROGRAM"); - try { - ProjectExtensionUtil.BeginLoadOperation (); - if (aname != null) { - // It is a project - monitor.BeginTask ("Loading '" + fileName + "'", 0); - DotNetAssemblyProject project = new DotNetAssemblyProject ("C#"); - MonoSolutionItemHandler handler = new MonoSolutionItemHandler (project); - ProjectExtensionUtil.InstallHandler (handler, project); - project.Name = Path.GetFileName (basePath); - handler.Read (mkfile); - monitor.EndTask (); - return project; - } else { - string subdirs; - StringBuilder subdirsBuilder = new StringBuilder (); - subdirsBuilder.Append (mkfile.GetVariable ("common_dirs")); - if (subdirsBuilder.Length != 0) { - subdirsBuilder.Append ("\t"); - subdirsBuilder.Append (mkfile.GetVariable ("net_2_0_dirs")); - } - if (subdirsBuilder.Length == 0) - subdirsBuilder.Append (mkfile.GetVariable ("SUBDIRS")); + try { + ProjectExtensionUtil.BeginLoadOperation (); + if (aname != null) { + // It is a project + monitor.BeginTask ("Loading '" + fileName + "'", 0); + MakefileProject project = new MakefileProject ("C#"); + project.Name = Path.GetFileName (basePath); + project.Read (mkfile); + monitor.EndTask (); + return project; + } else { + string subdirs; + StringBuilder subdirsBuilder = new StringBuilder (); + subdirsBuilder.Append (mkfile.GetVariable ("common_dirs")); + if (subdirsBuilder.Length != 0) { + subdirsBuilder.Append ("\t"); + subdirsBuilder.Append (mkfile.GetVariable ("net_2_0_dirs")); + } + if (subdirsBuilder.Length == 0) + subdirsBuilder.Append (mkfile.GetVariable ("SUBDIRS")); - subdirs = subdirsBuilder.ToString (); - if (subdirs != null && (subdirs = subdirs.Trim (' ','\t')) != "") - { - object retObject; - SolutionFolder folder; - if (!hasParentSolution) { - Solution sol = new Solution (); - sol.ConvertToFormat (Services.ProjectService.FileFormats.GetFileFormat ("MonoMakefile"), false); - sol.FileName = fileName; - folder = sol.RootFolder; - retObject = sol; + subdirs = subdirsBuilder.ToString (); + if (subdirs != null && (subdirs = subdirs.Trim (' ', '\t')) != "") { + object retObject; + SolutionFolder folder; + if (!hasParentSolution) { + Solution sol = new Solution (); + sol.ConvertToFormat (Services.ProjectService.FileFormats.GetFileFormat ("MonoMakefile"), false); + sol.FileName = fileName; + folder = sol.RootFolder; + retObject = sol; - foreach (string conf in MonoMakefileFormat.Configurations) { - SolutionConfiguration sc = new SolutionConfiguration (conf); - sol.Configurations.Add (sc); + foreach (string conf in MonoMakefileFormat.Configurations) { + SolutionConfiguration sc = new SolutionConfiguration (conf); + sol.Configurations.Add (sc); + } + } else { + folder = new SolutionFolder (); + folder.Name = Path.GetFileName (Path.GetDirectoryName (fileName)); + retObject = folder; } - } else { - folder = new SolutionFolder (); - folder.Name = Path.GetFileName (Path.GetDirectoryName (fileName)); - retObject = folder; - } - subdirs = subdirs.Replace ('\t',' '); - string[] dirs = subdirs.Split (' '); + subdirs = subdirs.Replace ('\t', ' '); + string[] dirs = subdirs.Split (' '); - monitor.BeginTask ("Loading '" + fileName + "'", dirs.Length); - Hashtable added = new Hashtable (); - foreach (string dir in dirs) { - if (added.Contains (dir)) continue; - added.Add (dir, dir); - monitor.Step (1); - if (dir == null) continue; - string tdir = dir.Trim (); - if (tdir == "") continue; - string mfile = Path.Combine (Path.Combine (basePath, tdir), "Makefile"); - if (File.Exists (mfile) && CanReadFile (mfile, typeof(SolutionItem))) { - SolutionItem it = (SolutionItem) ReadFile (mfile, true, monitor); - folder.Items.Add (it); + monitor.BeginTask ("Loading '" + fileName + "'", dirs.Length); + Hashtable added = new Hashtable (); + foreach (string dir in dirs) { + if (added.Contains (dir)) + continue; + added.Add (dir, dir); + monitor.Step (1); + if (dir == null) + continue; + string tdir = dir.Trim (); + if (tdir == "") + continue; + string mfile = Path.Combine (Path.Combine (basePath, tdir), "Makefile"); + if (File.Exists (mfile) && CanReadFile (mfile, typeof(SolutionFolderItem))) { + SolutionFolderItem it = (SolutionFolderItem)ReadFile (mfile, true, monitor).Result; + folder.Items.Add (it); + } } + monitor.EndTask (); + return retObject; } - monitor.EndTask (); - return retObject; } + } finally { + ProjectExtensionUtil.EndLoadOperation (); } - } finally { - ProjectExtensionUtil.EndLoadOperation (); - } - return null; + return null; + }); } - public static bool IsMonoProject (object obj) - { - DotNetProject p = obj as DotNetProject; - return p != null && (ProjectExtensionUtil.GetItemHandler (p) is MonoSolutionItemHandler); - } - - public void ConvertToFormat (object obj) + public Task ConvertToFormat (object obj) { - // Nothing can be converted to this format. + return Task.FromResult (0); } public bool SupportsMixedFormats { diff --git a/main/src/addins/MonoDeveloperExtensions/MonoSolutionItemHandler.cs b/main/src/addins/MonoDeveloperExtensions/MonoSolutionItemHandler.cs index d43e15eb86..9636ac7e1c 100644 --- a/main/src/addins/MonoDeveloperExtensions/MonoSolutionItemHandler.cs +++ b/main/src/addins/MonoDeveloperExtensions/MonoSolutionItemHandler.cs @@ -36,6 +36,7 @@ using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Ide; using MonoDevelop.Projects; using MonoDevelop.Projects.Extensions; +using System.Threading.Tasks; namespace MonoDeveloper { @@ -73,8 +74,9 @@ namespace MonoDeveloper } } - public void Save (MonoDevelop.Core.IProgressMonitor monitor) + public Task Save (MonoDevelop.Core.ProgressMonitor monitor) { + return Task.FromResult (0); } internal void Read (MonoMakefile mkfile) @@ -171,7 +173,7 @@ namespace MonoDeveloper static Regex regexError = new Regex (@"^(\s*(?<file>.*)\((?<line>\d*)(,(?<column>\d*[\+]*))?\)(:|)\s+)*(?<level>\w+)\s*(?<number>.*):\s(?<message>.*)", RegexOptions.Compiled | RegexOptions.ExplicitCapture); - public BuildResult RunTarget (MonoDevelop.Core.IProgressMonitor monitor, string target, ConfigurationSelector configuration) + public Task<BuildResult> RunTarget (MonoDevelop.Core.ProgressMonitor monitor, string target, ConfigurationSelector configuration) { if (target == ProjectService.BuildTarget) target = "all"; @@ -180,28 +182,30 @@ namespace MonoDeveloper DotNetProjectConfiguration conf = (DotNetProjectConfiguration) project.GetConfiguration (configuration); - using (var output = new StringWriter ()) { - using (var tw = new LogTextWriter ()) { - tw.ChainWriter (output); - tw.ChainWriter (monitor.Log); + return Task<BuildResult>.Factory.StartNew (delegate { + using (var output = new StringWriter ()) { + using (var tw = new LogTextWriter ()) { + tw.ChainWriter (output); + tw.ChainWriter (monitor.Log); - using (ProcessWrapper proc = Runtime.ProcessService.StartProcess ("make", "PROFILE=" + conf.Id + " " + target, conf.OutputDirectory, monitor.Log, tw, null)) - proc.WaitForOutput (); + using (ProcessWrapper proc = Runtime.ProcessService.StartProcess ("make", "PROFILE=" + conf.Id + " " + target, conf.OutputDirectory, monitor.Log, tw, null)) + proc.WaitForOutput (); - tw.UnchainWriter (output); - tw.UnchainWriter (monitor.Log); + tw.UnchainWriter (output); + tw.UnchainWriter (monitor.Log); - CompilerResults cr = new CompilerResults (null); - string[] lines = output.ToString().Split ('\n'); - foreach (string line in lines) { - CompilerError err = CreateErrorFromString (line); - if (err != null) cr.Errors.Add (err); - } + CompilerResults cr = new CompilerResults (null); + string[] lines = output.ToString ().Split ('\n'); + foreach (string line in lines) { + CompilerError err = CreateErrorFromString (line); + if (err != null) + cr.Errors.Add (err); + } - return new BuildResult (cr, output.ToString()); + return new BuildResult (cr, output.ToString ()); + } } - } - + }); } private CompilerError CreateErrorFromString (string error_string) diff --git a/main/src/addins/MonoDeveloperExtensions/NUnit/MonoTestProvider.cs b/main/src/addins/MonoDeveloperExtensions/NUnit/MonoTestProvider.cs index 026631b786..8d38969172 100644 --- a/main/src/addins/MonoDeveloperExtensions/NUnit/MonoTestProvider.cs +++ b/main/src/addins/MonoDeveloperExtensions/NUnit/MonoTestProvider.cs @@ -36,19 +36,16 @@ namespace MonoDeveloper { class MonoTestProvider: ITestProvider { - public UnitTest CreateUnitTest (IWorkspaceObject entry) + public UnitTest CreateUnitTest (WorkspaceObject entry) { - if (entry is DotNetProject) { - DotNetProject project = (DotNetProject) entry; - MonoSolutionItemHandler handler = ProjectExtensionUtil.GetItemHandler (project) as MonoSolutionItemHandler; - if (handler != null) { - if (handler.UnitTest != null) - return (UnitTest) handler.UnitTest; - string testFileBase = handler.GetTestFileBase (); - UnitTest testSuite = new MonoTestSuite (project, project.Name, testFileBase); - handler.UnitTest = testSuite; - return testSuite; - } + if (entry is MakefileProject) { + var project = (MakefileProject) entry; + if (project.UnitTest != null) + return (UnitTest) project.UnitTest; + string testFileBase = project.GetTestFileBase (); + UnitTest testSuite = new MonoTestSuite (project, project.Name, testFileBase); + project.UnitTest = testSuite; + return testSuite; } return null; } @@ -63,7 +60,7 @@ namespace MonoDeveloper { string basePath; - public MonoTestSuite (Project p, string name, string basePath): base (name, p) + public MonoTestSuite (MakefileProject p, string name, string basePath): base (name, p) { this.basePath = basePath; } diff --git a/main/src/addins/NUnit/Commands/NUnitCommands.cs b/main/src/addins/NUnit/Commands/NUnitCommands.cs index f0d9322df4..22f6ebb2d3 100644 --- a/main/src/addins/NUnit/Commands/NUnitCommands.cs +++ b/main/src/addins/NUnit/Commands/NUnitCommands.cs @@ -64,7 +64,7 @@ namespace MonoDevelop.NUnit.Commands { protected override void Run () { - IWorkspaceObject ob = IdeApp.ProjectOperations.CurrentSelectedBuildTarget; + WorkspaceObject ob = IdeApp.ProjectOperations.CurrentSelectedObject; if (ob != null) { UnitTest test = NUnitService.Instance.FindRootTest (ob); if (test != null) @@ -74,7 +74,7 @@ namespace MonoDevelop.NUnit.Commands protected override void Update (CommandInfo info) { - IWorkspaceObject ob = IdeApp.ProjectOperations.CurrentSelectedBuildTarget; + WorkspaceObject ob = IdeApp.ProjectOperations.CurrentSelectedObject; if (ob != null) { UnitTest test = NUnitService.Instance.FindRootTest (ob); info.Enabled = (test != null); diff --git a/main/src/addins/NUnit/Gui/NUnitAssemblyGroupConfigurationNodeBuilder.cs b/main/src/addins/NUnit/Gui/NUnitAssemblyGroupConfigurationNodeBuilder.cs index 1d7c6e5a4e..bea7c43faa 100644 --- a/main/src/addins/NUnit/Gui/NUnitAssemblyGroupConfigurationNodeBuilder.cs +++ b/main/src/addins/NUnit/Gui/NUnitAssemblyGroupConfigurationNodeBuilder.cs @@ -122,7 +122,7 @@ namespace MonoDevelop.NUnit foreach (string file in dlg.SelectedFiles) config.Assemblies.Add (new TestAssembly (file)); - IdeApp.Workspace.Save(); + IdeApp.Workspace.SaveAsync(); } } } diff --git a/main/src/addins/NUnit/Gui/NUnitAssemblyGroupNodeBuilder.cs b/main/src/addins/NUnit/Gui/NUnitAssemblyGroupNodeBuilder.cs index 490a355404..2cc8a48c5e 100644 --- a/main/src/addins/NUnit/Gui/NUnitAssemblyGroupNodeBuilder.cs +++ b/main/src/addins/NUnit/Gui/NUnitAssemblyGroupNodeBuilder.cs @@ -117,7 +117,7 @@ namespace MonoDevelop.NUnit NUnitAssemblyGroupProject project = CurrentNode.DataItem as NUnitAssemblyGroupProject; project.ParentFolder.Items.Remove (project); project.Dispose (); - IdeApp.Workspace.Save (); + IdeApp.Workspace.SaveAsync (); } } } diff --git a/main/src/addins/NUnit/Gui/TestPad.cs b/main/src/addins/NUnit/Gui/TestPad.cs index 9b2c1fc7c3..15ece94e07 100644 --- a/main/src/addins/NUnit/Gui/TestPad.cs +++ b/main/src/addins/NUnit/Gui/TestPad.cs @@ -44,6 +44,7 @@ using MonoDevelop.Projects; using Mono.TextEditor; using System.Linq; using MonoDevelop.Components; +using MonoDevelop.Ide.Commands; namespace MonoDevelop.NUnit { @@ -51,7 +52,7 @@ namespace MonoDevelop.NUnit { NUnitService testService = NUnitService.Instance; - IAsyncOperation runningTestOperation; + AsyncOperation runningTestOperation; VPaned paned; TreeView detailsTree; ListStore detailsStore; @@ -411,7 +412,7 @@ namespace MonoDevelop.NUnit { UnitTest test = GetSelectedTest (); if (test != null) { - SolutionEntityItem item = test.OwnerObject as SolutionEntityItem; + SolutionItem item = test.OwnerObject as SolutionItem; ExecutionModeCommandService.GenerateExecutionModeCommands ( item, test.CanRun, @@ -467,12 +468,12 @@ namespace MonoDevelop.NUnit return nav.DataItem as UnitTest; } - public IAsyncOperation RunTest (UnitTest test, IExecutionHandler mode) + public AsyncOperation RunTest (UnitTest test, IExecutionHandler mode) { return RunTest (FindTestNode (test), mode, false); } - IAsyncOperation RunTest (ITreeNavigator nav, IExecutionHandler mode, bool bringToFront = true) + AsyncOperation RunTest (ITreeNavigator nav, IExecutionHandler mode, bool bringToFront = true) { if (nav == null) return null; @@ -487,7 +488,7 @@ namespace MonoDevelop.NUnit if (bringToFront) IdeApp.Workbench.GetPad<TestPad> ().BringToFront (); runningTestOperation = testService.RunTest (test, mode); - runningTestOperation.Completed += (OperationHandler) DispatchService.GuiDispatch (new OperationHandler (OnTestSessionCompleted)); + runningTestOperation.Task.ContinueWith (t => OnTestSessionCompleted ()); return runningTestOperation; } @@ -501,10 +502,9 @@ namespace MonoDevelop.NUnit RunTest (TreeView.GetSelectedNode (), mode); } - void OnTestSessionCompleted (IAsyncOperation op) + void OnTestSessionCompleted () { - if (op.Success) - RefreshDetails (); + RefreshDetails (); runningTestOperation = null; this.buttonRunAll.Sensitive = true; this.buttonStop.Sensitive = false; diff --git a/main/src/addins/NUnit/Gui/TestResultsPad.cs b/main/src/addins/NUnit/Gui/TestResultsPad.cs index 1baf8b81e5..00c4fa75ea 100644 --- a/main/src/addins/NUnit/Gui/TestResultsPad.cs +++ b/main/src/addins/NUnit/Gui/TestResultsPad.cs @@ -42,6 +42,8 @@ using MonoDevelop.Components.Docking; using MonoDevelop.Ide; using System.Text.RegularExpressions; using MonoDevelop.Components; +using System.Threading; +using MonoDevelop.Ide.Commands; namespace MonoDevelop.NUnit { @@ -475,7 +477,34 @@ namespace MonoDevelop.NUnit } } } - + + [CommandHandler (EditCommands.Copy)] + protected void OnCopy () + { + UnitTest test = GetSelectedTest (); + if (test != null) { + var last = test.GetLastResult (); + if (last == null) + return; + var clipboard = Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false)); + clipboard.Text = last.StackTrace; + } + } + + [CommandUpdateHandler (EditCommands.Copy)] + protected void OnUpdateCopy (CommandInfo info) + { + UnitTest test = GetSelectedTest (); + if (test != null) { + var result = test.GetLastResult (); + if (result != null) { + info.Enabled = !string.IsNullOrEmpty (result.StackTrace); + return; + } + } + info.Enabled = false; + } + [CommandHandler (TestCommands.SelectTestInTree)] protected void OnSelectTestInTree () { @@ -704,11 +733,14 @@ namespace MonoDevelop.NUnit { ITestProgressMonitor monitor; TestResultsPad pad; + CancellationTokenSource cs; - public TestMonitor (TestResultsPad pad) + public TestMonitor (TestResultsPad pad, CancellationTokenSource cs) { this.pad = pad; this.monitor = pad; + this.cs = cs; + cs.Token.Register (Cancel); } public void InitializeTestRun (UnitTest test) { diff --git a/main/src/addins/NUnit/Makefile.am b/main/src/addins/NUnit/Makefile.am index 4b4491f083..3ae131ae68 100644 --- a/main/src/addins/NUnit/Makefile.am +++ b/main/src/addins/NUnit/Makefile.am @@ -1,4 +1,3 @@ SUBDIRS = NUnitRunner . include $(top_srcdir)/xbuild.include -EXTRA_DIST += lib/nunit.core.dll lib/nunit.core.interfaces.dll lib/nunit.framework.dll lib/nunit.util.dll diff --git a/main/src/addins/NUnit/MonoDevelop.NUnit.csproj b/main/src/addins/NUnit/MonoDevelop.NUnit.csproj index ae8af1922d..2a2aa548c8 100644 --- a/main/src/addins/NUnit/MonoDevelop.NUnit.csproj +++ b/main/src/addins/NUnit/MonoDevelop.NUnit.csproj @@ -39,12 +39,6 @@ <DocumentationFile>..\..\..\build\AddIns\NUnit\MonoDevelop.NUnit.xml</DocumentationFile> </PropertyGroup> <ItemGroup> - <Reference Include="nunit.core"> - <HintPath>lib\nunit.core.dll</HintPath> - </Reference> - <Reference Include="nunit.framework"> - <HintPath>lib\nunit.framework.dll</HintPath> - </Reference> <Reference Include="System" /> <Reference Include="System.Xml" /> <Reference Include="glade-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f"> @@ -67,14 +61,20 @@ </Reference> <Reference Include="Mono.Posix" /> <Reference Include="Mono.Cairo" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Core" /> + <Reference Include="nunit.framework"> + <HintPath>..\..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath> + </Reference> + <Reference Include="nunit.core"> + <HintPath>..\..\..\packages\NUnit.Runners.2.6.3\tools\lib\nunit.core.dll</HintPath> + </Reference> <Reference Include="nunit.core.interfaces"> - <HintPath>lib\nunit.core.interfaces.dll</HintPath> + <HintPath>..\..\..\packages\NUnit.Runners.2.6.3\tools\lib\nunit.core.interfaces.dll</HintPath> </Reference> <Reference Include="nunit.util"> - <HintPath>lib\nunit.util.dll</HintPath> + <HintPath>..\..\..\packages\NUnit.Runners.2.6.3\tools\lib\nunit.util.dll</HintPath> </Reference> - <Reference Include="System.Xml.Linq" /> - <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\core\MonoDevelop.Core\MonoDevelop.Core.csproj"> @@ -247,6 +247,14 @@ </ItemGroup> <ItemGroup> <None Include="Makefile.am" /> + <None Include="packages.config" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> + <Target Name="BeforeBuild"> + <PropertyGroup> + <NuGet>$(SolutionDir)\external\nuget-binary\NuGet.exe</NuGet> + <NuGet Condition="$(OS)=='Unix'">mono $(NuGet)</NuGet> + </PropertyGroup> + <Exec Condition="Exists('$(SolutionDir)\..\.git')" Command="$(NuGet) restore -SolutionDirectory $(SolutionDir)" /> + </Target> </Project> diff --git a/main/src/addins/NUnit/MonoDevelopNUnit.addin.xml b/main/src/addins/NUnit/MonoDevelopNUnit.addin.xml index f2af6ec39c..d0e267a3d7 100644 --- a/main/src/addins/NUnit/MonoDevelopNUnit.addin.xml +++ b/main/src/addins/NUnit/MonoDevelopNUnit.addin.xml @@ -50,16 +50,6 @@ <!-- Extensions --> - <Extension path="/MonoDevelop/Core/SupportPackages"> - <Condition id="PackageNotInstalled" name="mono-nunit" version="2.7"> - <Package name="nunit" version="2.4" clrVersion="Default"> - <Assembly file="nunit.core.dll" /> - <Assembly file="nunit.core.interfaces.dll" /> - <Assembly file="nunit.framework.dll" /> - </Package> - </Condition> - </Extension> - <Extension path = "/MonoDevelop/Ide/Pads"> <SolutionPad id = "MonoDevelop.NUnit.TestPad" defaultLayout="*" defaultPlacement = "Right" defaultStatus="AutoHide" _label = "Unit Tests" icon = "nunit-pad-icon" class = "MonoDevelop.NUnit.TestPad"> <PadOption id = "ShowTestTime" _label = "Show Test Time" defaultValue = "False" /> @@ -146,6 +136,8 @@ <CommandItem id = "MonoDevelop.NUnit.Commands.TestCommands.GoToFailure" /> <CommandItem id = "MonoDevelop.NUnit.Commands.TestCommands.ShowTestCode" /> <CommandItem id = "MonoDevelop.NUnit.Commands.TestCommands.SelectTestInTree" /> + <SeparatorItem id = "s1" /> + <CommandItem id = "MonoDevelop.Ide.Commands.EditCommands.Copy" /> </Extension> <Extension path = "/MonoDevelop/NUnit/ContextMenu/TestChart"> @@ -190,8 +182,8 @@ <StockIcon stockid = "nunit-run" resource = "unit-run-light-16.png" size="Menu" /> </Extension> - <Extension path = "/MonoDevelop/ProjectModel/ProjectServiceExtensions"> - <Class class = "MonoDevelop.NUnit.NUnitProjectServiceExtension" /> + <Extension path = "/MonoDevelop/ProjectModel/ProjectModelExtensions"> + <ProjectExtension class = "MonoDevelop.NUnit.NUnitProjectServiceExtension" /> </Extension> <Extension path = "/MonoDevelop/ProjectModel/SerializableClasses"> diff --git a/main/src/addins/NUnit/NUnitRunner/NUnitRunner.csproj b/main/src/addins/NUnit/NUnitRunner/NUnitRunner.csproj index 68153a46ba..2248340e29 100644 --- a/main/src/addins/NUnit/NUnitRunner/NUnitRunner.csproj +++ b/main/src/addins/NUnit/NUnitRunner/NUnitRunner.csproj @@ -37,18 +37,28 @@ <ItemGroup> <Reference Include="System" /> <Reference Include="System.Xml" /> - <Reference Include="nunit.core"> - <HintPath>..\lib\nunit.core.dll</HintPath> - </Reference> <Reference Include="nunit.framework"> - <HintPath>..\lib\nunit.framework.dll</HintPath> + <HintPath>..\..\..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath> + </Reference> + <Reference Include="nunit.core"> + <HintPath>..\..\..\..\packages\NUnit.Runners.2.6.3\tools\lib\nunit.core.dll</HintPath> </Reference> <Reference Include="nunit.core.interfaces"> - <HintPath>..\lib\nunit.core.interfaces.dll</HintPath> + <HintPath>..\..\..\..\packages\NUnit.Runners.2.6.3\tools\lib\nunit.core.interfaces.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> <Compile Include="NUnitTestRunner.cs" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> -</Project>
\ No newline at end of file + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> + <Target Name="BeforeBuild"> + <PropertyGroup> + <NuGet>$(SolutionDir)\external\nuget-binary\NuGet.exe</NuGet> + <NuGet Condition="$(OS)=='Unix'">mono $(NuGet)</NuGet> + </PropertyGroup> + <Exec Condition="Exists('$(SolutionDir)\..\.git')" Command="$(NuGet) restore -SolutionDirectory $(SolutionDir)" /> + </Target> +</Project> diff --git a/main/src/addins/NUnit/NUnitRunner/packages.config b/main/src/addins/NUnit/NUnitRunner/packages.config new file mode 100644 index 0000000000..3ca92b52ea --- /dev/null +++ b/main/src/addins/NUnit/NUnitRunner/packages.config @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="NUnit" version="2.6.3" targetFramework="net40" />
+ <package id="NUnit.Runners" version="2.6.3" targetFramework="net40" />
+</packages>
\ No newline at end of file diff --git a/main/src/addins/NUnit/Project/NUnitAssemblyGroupProject.cs b/main/src/addins/NUnit/Project/NUnitAssemblyGroupProject.cs index 0a67aac29d..561ede1a8a 100644 --- a/main/src/addins/NUnit/Project/NUnitAssemblyGroupProject.cs +++ b/main/src/addins/NUnit/Project/NUnitAssemblyGroupProject.cs @@ -38,7 +38,7 @@ using MonoDevelop.Ide.TypeSystem; namespace MonoDevelop.NUnit { [DataInclude (typeof(NUnitAssemblyGroupProjectConfiguration))] - public class NUnitAssemblyGroupProject: SolutionEntityItem + public class NUnitAssemblyGroupProject: SolutionItem { RootTest rootTest; @@ -53,7 +53,7 @@ namespace MonoDevelop.NUnit Configurations.Add (CreateConfiguration ("Default")); } - public override void InitializeFromTemplate (XmlElement element) + protected override void OnInitializeFromTemplate (XmlElement element) { Configurations.Add (CreateConfiguration ("Default")); } @@ -73,28 +73,6 @@ namespace MonoDevelop.NUnit conf.Name = name; return conf; } - - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) - { - } - - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) - { - return null; - } - - protected override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) - { - } - - protected override bool OnGetNeedsBuilding (ConfigurationSelector configuration) - { - return false; - } - - protected override void OnSetNeedsBuilding (bool value, ConfigurationSelector configuration) - { - } } public class NUnitAssemblyGroupProjectConfiguration: SolutionItemConfiguration diff --git a/main/src/addins/NUnit/Services/ITestProvider.cs b/main/src/addins/NUnit/Services/ITestProvider.cs index b9cd72530d..c2bea5f998 100644 --- a/main/src/addins/NUnit/Services/ITestProvider.cs +++ b/main/src/addins/NUnit/Services/ITestProvider.cs @@ -35,7 +35,7 @@ namespace MonoDevelop.NUnit { public interface ITestProvider { - UnitTest CreateUnitTest (IWorkspaceObject entry); + UnitTest CreateUnitTest (WorkspaceObject entry); Type[] GetOptionTypes (); } } diff --git a/main/src/addins/NUnit/Services/NUnitAssemblyTestSuite.cs b/main/src/addins/NUnit/Services/NUnitAssemblyTestSuite.cs index 3e55a824be..895b07674d 100644 --- a/main/src/addins/NUnit/Services/NUnitAssemblyTestSuite.cs +++ b/main/src/addins/NUnit/Services/NUnitAssemblyTestSuite.cs @@ -45,6 +45,7 @@ using MonoDevelop.Ide; using System.Xml.Linq; using System.Linq; using System.Globalization; +using System.Threading.Tasks; namespace MonoDevelop.NUnit { @@ -69,7 +70,7 @@ namespace MonoDevelop.NUnit { } - public NUnitAssemblyTestSuite (string name, SolutionItem ownerSolutionItem): base (name, ownerSolutionItem) + public NUnitAssemblyTestSuite (string name, WorkspaceObject ownerSolutionItem): base (name, ownerSolutionItem) { } @@ -145,10 +146,9 @@ namespace MonoDevelop.NUnit } } - public override IAsyncOperation Refresh () + public override Task Refresh (CancellationToken ct) { - AsyncOperation oper = new AsyncOperation (); - System.Threading.ThreadPool.QueueUserWorkItem (delegate { + return Task.Factory.StartNew (delegate { lock (locker) { try { while (Status == TestStatus.Loading) { @@ -162,13 +162,10 @@ namespace MonoDevelop.NUnit Monitor.Wait (locker); } } - oper.SetCompleted (true); } catch { - oper.SetCompleted (false); } } }); - return oper; } DateTime GetAssemblyTime () diff --git a/main/src/addins/NUnit/Services/NUnitProjectServiceExtension.cs b/main/src/addins/NUnit/Services/NUnitProjectServiceExtension.cs index 0ecd719fd8..ff59f13226 100644 --- a/main/src/addins/NUnit/Services/NUnitProjectServiceExtension.cs +++ b/main/src/addins/NUnit/Services/NUnitProjectServiceExtension.cs @@ -28,44 +28,32 @@ using MonoDevelop.Core; using MonoDevelop.Projects; using MonoDevelop.Ide; +using System.Threading.Tasks; namespace MonoDevelop.NUnit { - public class NUnitProjectServiceExtension: ProjectServiceExtension + public class NUnitProjectServiceExtension: ProjectExtension { - public override void Execute (MonoDevelop.Core.IProgressMonitor monitor, IBuildTarget item, ExecutionContext context, ConfigurationSelector configuration) + protected override Task OnExecute (MonoDevelop.Core.ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { - if (base.CanExecute (item, context, configuration)) { + if (base.OnGetCanExecute (context, configuration)) { // It is executable by default - base.Execute(monitor, item, context, configuration); - return; - } else if (item is IWorkspaceObject) { - UnitTest test = NUnitService.Instance.FindRootTest ((IWorkspaceObject)item); - if (test != null) { - IAsyncOperation oper = null; - DispatchService.GuiSyncDispatch (delegate { - oper = NUnitService.Instance.RunTest (test, context.ExecutionHandler, false); - }); -// if (oper != null) { -// monitor.CancelRequested += delegate { -// oper.Cancel (); -// }; -// oper.WaitForCompleted (); -// } - } + return base.OnExecute (monitor, context, configuration); } + UnitTest test = NUnitService.Instance.FindRootTest (Project); + if (test != null) + return NUnitService.Instance.RunTest (test, context.ExecutionHandler, false).Task; + else + return Task.FromResult (0); } - public override bool CanExecute (IBuildTarget item, ExecutionContext context, ConfigurationSelector configuration) + protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) { // We check for DefaultExecutionHandlerFactory because the tests can't run using any other execution mode - bool res = base.CanExecute (item, context, configuration); - if (!res && (item is IWorkspaceObject)) { - UnitTest test = NUnitService.Instance.FindRootTest ((IWorkspaceObject)item); - return (test != null) && test.CanRun (context.ExecutionHandler); - } else - return res; + bool res = base.OnGetCanExecute (context, configuration); + UnitTest test = NUnitService.Instance.FindRootTest (Project); + return (test != null) && test.CanRun (context.ExecutionHandler); } } } diff --git a/main/src/addins/NUnit/Services/NUnitService.cs b/main/src/addins/NUnit/Services/NUnitService.cs index c5a2407532..79877e0fc4 100644 --- a/main/src/addins/NUnit/Services/NUnitService.cs +++ b/main/src/addins/NUnit/Services/NUnitService.cs @@ -38,6 +38,8 @@ using MonoDevelop.Projects; using NUnit.Core; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide; +using System.Threading.Tasks; +using System.Linq; namespace MonoDevelop.NUnit { @@ -99,14 +101,20 @@ namespace MonoDevelop.NUnit } } - public IAsyncOperation RunTest (UnitTest test, IExecutionHandler context) + public AsyncOperation RunTest (UnitTest test, IExecutionHandler context) { var result = RunTest (test, context, IdeApp.Preferences.BuildBeforeRunningTests); - result.Completed += (OperationHandler) DispatchService.GuiDispatch (new OperationHandler (OnTestSessionCompleted)); + result.Task.ContinueWith (t => OnTestSessionCompleted ()); return result; } - public IAsyncOperation RunTest (UnitTest test, IExecutionHandler context, bool buildOwnerObject) + public AsyncOperation RunTest (UnitTest test, IExecutionHandler context, bool buildOwnerObject) + { + var cs = new CancellationTokenSource (); + return new AsyncOperation (RunTestAsync (test, context, buildOwnerObject, cs), cs); + } + + async Task RunTestAsync (UnitTest test, IExecutionHandler context, bool buildOwnerObject, CancellationTokenSource cs) { string testName = test.FullName; @@ -115,39 +123,23 @@ namespace MonoDevelop.NUnit if (bt != null && bt.NeedsBuilding (IdeApp.Workspace.ActiveConfiguration)) { if (!IdeApp.ProjectOperations.CurrentRunOperation.IsCompleted) { MonoDevelop.Ide.Commands.StopHandler.StopBuildOperations (); - IdeApp.ProjectOperations.CurrentRunOperation.WaitForCompleted (); + await IdeApp.ProjectOperations.CurrentRunOperation.Task; } - AsyncOperation retOper = new AsyncOperation (); - - IAsyncOperation op = IdeApp.ProjectOperations.Build (bt); - retOper.TrackOperation (op, false); - - op.Completed += delegate { - // The completed event of the build operation is run in the gui thread, - // so we need a new thread, because refreshing must be async - System.Threading.ThreadPool.QueueUserWorkItem (delegate { - if (op.Success) { - RefreshTests (); - test = SearchTest (testName); - if (test != null) { - Gtk.Application.Invoke (delegate { - // RunTest must run in the gui thread - retOper.TrackOperation (RunTest (test, context, false), true); - }); - } - else - retOper.SetCompleted (false); - } - }); - }; - - return retOper; + var res = await IdeApp.ProjectOperations.Build (bt, cs.Token).Task; + if (res.HasErrors) + return; + + await RefreshTests (cs.Token); + test = SearchTest (testName); + if (test != null) + await RunTestAsync (test, context, false, cs); + return; } } if (!IdeApp.ProjectOperations.ConfirmExecutionOperation ()) - return NullProcessAsyncOperation.Failure; + return; Pad resultsPad = IdeApp.Workbench.GetPad <TestResultsPad>(); if (resultsPad == null) { @@ -160,25 +152,17 @@ namespace MonoDevelop.NUnit resultsPad.Sticky = true; resultsPad.BringToFront (); - TestSession session = new TestSession (test, context, (TestResultsPad) resultsPad.Content); - - session.Completed += delegate { - Gtk.Application.Invoke (delegate { - resultsPad.Sticky = false; - }); - }; - - session.Start (); - + TestSession session = new TestSession (test, context, (TestResultsPad) resultsPad.Content, cs); IdeApp.ProjectOperations.CurrentRunOperation = session; - - return session; + + await session.Start (); + + resultsPad.Sticky = false; } - public void RefreshTests () + public Task RefreshTests (CancellationToken ct) { - foreach (UnitTest t in RootTests) - t.Refresh ().WaitForCompleted (); + return Task.WhenAll (RootTests.Select (t => t.Refresh (ct))); } public UnitTest SearchTest (string fullName) @@ -238,12 +222,12 @@ namespace MonoDevelop.NUnit return null; } - public UnitTest FindRootTest (IWorkspaceObject item) + public UnitTest FindRootTest (WorkspaceObject item) { return FindRootTest (RootTests, item); } - public UnitTest FindRootTest (IEnumerable<UnitTest> tests, IWorkspaceObject item) + public UnitTest FindRootTest (IEnumerable<UnitTest> tests, WorkspaceObject item) { foreach (UnitTest t in tests) { if (t.OwnerObject == item) @@ -281,7 +265,7 @@ namespace MonoDevelop.NUnit NotifyTestSuiteChanged (); } - public UnitTest BuildTest (IWorkspaceObject entry) + public UnitTest BuildTest (WorkspaceObject entry) { foreach (ITestProvider p in providers) { try { @@ -325,7 +309,7 @@ namespace MonoDevelop.NUnit public event EventHandler TestSuiteChanged; - void OnTestSessionCompleted (IAsyncOperation op) + void OnTestSessionCompleted () { var handler = TestSessionCompleted; if (handler != null) @@ -337,31 +321,28 @@ namespace MonoDevelop.NUnit - class TestSession: IAsyncOperation, ITestProgressMonitor + class TestSession: AsyncOperation, ITestProgressMonitor { UnitTest test; TestMonitor monitor; Thread runThread; bool success; - ManualResetEvent waitEvent; IExecutionHandler context; TestResultsPad resultsPad; - public TestSession (UnitTest test, IExecutionHandler context, TestResultsPad resultsPad) + public TestSession (UnitTest test, IExecutionHandler context, TestResultsPad resultsPad, CancellationTokenSource cs) { this.test = test; this.context = context; - this.monitor = new TestMonitor (resultsPad); + CancellationTokenSource = cs; + this.monitor = new TestMonitor (resultsPad, CancellationTokenSource); this.resultsPad = resultsPad; resultsPad.InitializeTestRun (test); } - public void Start () + public Task Start () { - runThread = new Thread (new ThreadStart (RunTests)); - runThread.Name = "NUnit test runner"; - runThread.IsBackground = true; - runThread.Start (); + return Task = Task.Factory.StartNew (RunTests); } void RunTests () @@ -381,12 +362,6 @@ namespace MonoDevelop.NUnit monitor.FinishTestRun (); runThread = null; } - lock (this) { - if (waitEvent != null) - waitEvent.Set (); - } - if (Completed != null) - Completed (this); } void ITestProgressMonitor.BeginTest (UnitTest test) @@ -412,45 +387,7 @@ namespace MonoDevelop.NUnit bool ITestProgressMonitor.IsCancelRequested { get { return monitor.IsCancelRequested; } } - - void IAsyncOperation.Cancel () - { - monitor.Cancel (); - } - - public void WaitForCompleted () - { - if (IsCompleted) return; - - if (DispatchService.IsGuiThread) { - while (!IsCompleted) { - while (Gtk.Application.EventsPending ()) - Gtk.Application.RunIteration (); - Thread.Sleep (100); - } - } else { - lock (this) { - if (waitEvent == null) - waitEvent = new ManualResetEvent (false); - } - waitEvent.WaitOne (); - } - } - - public bool IsCompleted { - get { return runThread == null; } - } - - public bool Success { - get { return success; } - } - public bool SuccessWithWarnings { - get { return false; } - } - - public event OperationHandler Completed; - public event TestHandler CancelRequested { add { monitor.CancelRequested += value; } remove { monitor.CancelRequested -= value; } diff --git a/main/src/addins/NUnit/Services/SolutionFolderTestGroup.cs b/main/src/addins/NUnit/Services/SolutionFolderTestGroup.cs index c961b9c7e8..384598bc45 100644 --- a/main/src/addins/NUnit/Services/SolutionFolderTestGroup.cs +++ b/main/src/addins/NUnit/Services/SolutionFolderTestGroup.cs @@ -81,7 +81,7 @@ namespace MonoDevelop.NUnit protected override void OnCreateTests () { NUnitService testService = NUnitService.Instance; - foreach (SolutionItem e in combine.Items) { + foreach (SolutionFolderItem e in combine.Items) { UnitTest t = testService.BuildTest (e); if (t != null) Tests.Add (t); diff --git a/main/src/addins/NUnit/Services/SystemTestProvider.cs b/main/src/addins/NUnit/Services/SystemTestProvider.cs index 9e60f7767a..4090e3fff2 100644 --- a/main/src/addins/NUnit/Services/SystemTestProvider.cs +++ b/main/src/addins/NUnit/Services/SystemTestProvider.cs @@ -34,7 +34,7 @@ namespace MonoDevelop.NUnit { public class SystemTestProvider: ITestProvider { - public UnitTest CreateUnitTest (IWorkspaceObject entry) + public UnitTest CreateUnitTest (WorkspaceObject entry) { UnitTest test = null; diff --git a/main/src/addins/NUnit/Services/UnitTest.cs b/main/src/addins/NUnit/Services/UnitTest.cs index f8e9816015..a0044ac0c7 100644 --- a/main/src/addins/NUnit/Services/UnitTest.cs +++ b/main/src/addins/NUnit/Services/UnitTest.cs @@ -34,6 +34,9 @@ using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; using MonoDevelop.Core.Execution; +using MonoDevelop.Ide; +using System.Threading.Tasks; +using System.Threading; namespace MonoDevelop.NUnit { @@ -45,8 +48,8 @@ namespace MonoDevelop.NUnit UnitTest parent; TestStatus status; Hashtable options; - IWorkspaceObject ownerSolutionItem; - SolutionEntityItem ownerSolutionEntityItem; + WorkspaceObject ownerSolutionItem; + SolutionItem ownerSolutionEntityItem; UnitTestResultsStore results; bool historicResult; bool resultLoaded; @@ -71,11 +74,11 @@ namespace MonoDevelop.NUnit this.name = name; } - protected UnitTest (string name, IWorkspaceObject ownerSolutionItem) + protected UnitTest (string name, WorkspaceObject ownerSolutionItem) { this.name = name; this.ownerSolutionItem = ownerSolutionItem; - ownerSolutionEntityItem = ownerSolutionItem as SolutionEntityItem; + ownerSolutionEntityItem = ownerSolutionItem as SolutionItem; if (ownerSolutionEntityItem != null) ownerSolutionEntityItem.DefaultConfigurationChanged += OnConfugurationChanged; } @@ -363,11 +366,11 @@ namespace MonoDevelop.NUnit } } - protected IWorkspaceObject OwnerSolutionItem { + protected WorkspaceObject OwnerSolutionItem { get { return ownerSolutionItem; } } - public IWorkspaceObject OwnerObject { + public WorkspaceObject OwnerObject { get { if (ownerSolutionItem != null) return ownerSolutionItem; @@ -390,11 +393,9 @@ namespace MonoDevelop.NUnit } // Forces the reloading of tests, if they have changed - public virtual IAsyncOperation Refresh () + public virtual Task Refresh (CancellationToken ct) { - AsyncOperation op = new AsyncOperation (); - op.SetCompleted (true); - return op; + return Task.FromResult (0); } public UnitTestResult Run (TestContext testContext) @@ -521,8 +522,8 @@ namespace MonoDevelop.NUnit oset.Tests.Remove (te); } } - - ce.Save (new NullProgressMonitor ()); + + IdeApp.ProjectOperations.SaveAsync ((WorkspaceObject)ce); } protected virtual ICollection OnLoadOptions (string configuration) @@ -552,8 +553,8 @@ namespace MonoDevelop.NUnit void GetOwnerSolutionItem (UnitTest t, out IConfigurationTarget c, out string path) { - if (OwnerSolutionItem is SolutionEntityItem) { - c = OwnerSolutionItem as SolutionEntityItem; + if (OwnerSolutionItem is SolutionItem) { + c = OwnerSolutionItem as SolutionItem; path = ""; } else if (parent != null) { parent.GetOwnerSolutionItem (t, out c, out path); diff --git a/main/src/addins/NUnit/Services/UnitTestGroup.cs b/main/src/addins/NUnit/Services/UnitTestGroup.cs index f478e1f00b..eaa541f83a 100644 --- a/main/src/addins/NUnit/Services/UnitTestGroup.cs +++ b/main/src/addins/NUnit/Services/UnitTestGroup.cs @@ -31,6 +31,8 @@ using MonoDevelop.Core; using MonoDevelop.Core.ProgressMonitoring; using System.Collections; using MonoDevelop.Projects; +using System.Threading.Tasks; +using System.Threading; namespace MonoDevelop.NUnit { @@ -42,7 +44,7 @@ namespace MonoDevelop.NUnit { } - protected UnitTestGroup (string name, IWorkspaceObject ownerSolutionItem): base (name, ownerSolutionItem) + protected UnitTestGroup (string name, WorkspaceObject ownerSolutionItem): base (name, ownerSolutionItem) { } @@ -121,13 +123,10 @@ namespace MonoDevelop.NUnit { } - public override IAsyncOperation Refresh () + public async override Task Refresh (CancellationToken ct) { - AggregatedAsyncOperation oper = new AggregatedAsyncOperation (); foreach (UnitTest t in Tests) - oper.Add (t.Refresh ()); - oper.StartMonitoring (); - return oper; + await t.Refresh (ct); } protected override UnitTestResult OnRun (TestContext testContext) diff --git a/main/src/addins/NUnit/lib/nunit.core.dll b/main/src/addins/NUnit/lib/nunit.core.dll Binary files differdeleted file mode 100644 index 5f748becd1..0000000000 --- a/main/src/addins/NUnit/lib/nunit.core.dll +++ /dev/null diff --git a/main/src/addins/NUnit/lib/nunit.core.interfaces.dll b/main/src/addins/NUnit/lib/nunit.core.interfaces.dll Binary files differdeleted file mode 100644 index 72b9486d74..0000000000 --- a/main/src/addins/NUnit/lib/nunit.core.interfaces.dll +++ /dev/null diff --git a/main/src/addins/NUnit/lib/nunit.framework.dll b/main/src/addins/NUnit/lib/nunit.framework.dll Binary files differdeleted file mode 100644 index eaea9eedf7..0000000000 --- a/main/src/addins/NUnit/lib/nunit.framework.dll +++ /dev/null diff --git a/main/src/addins/NUnit/lib/nunit.util.dll b/main/src/addins/NUnit/lib/nunit.util.dll Binary files differdeleted file mode 100644 index 28d603c662..0000000000 --- a/main/src/addins/NUnit/lib/nunit.util.dll +++ /dev/null diff --git a/main/src/addins/NUnit/packages.config b/main/src/addins/NUnit/packages.config new file mode 100644 index 0000000000..3ca92b52ea --- /dev/null +++ b/main/src/addins/NUnit/packages.config @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="NUnit" version="2.6.3" targetFramework="net40" />
+ <package id="NUnit.Runners" version="2.6.3" targetFramework="net40" />
+</packages>
\ No newline at end of file diff --git a/main/src/addins/NUnit/templates/NUnitProject.xpt.xml b/main/src/addins/NUnit/templates/NUnitProject.xpt.xml index 9a83ac6b23..4a42bb84fb 100644 --- a/main/src/addins/NUnit/templates/NUnitProject.xpt.xml +++ b/main/src/addins/NUnit/templates/NUnitProject.xpt.xml @@ -27,9 +27,12 @@ <References> <Reference type="Package" refto="System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> - <Reference type="Package" refto="nunit.framework" SpecificVersion = "false" LocalCopy = "false" /> </References> - + + <Packages> + <Package ID="NUnit" Version="2.6.3" /> + </Packages> + <Files> <CodeDomFile name="Test"> <CompileUnit> diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs index 824a06ed1a..c904caacf7 100644 --- a/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs +++ b/main/src/addins/TextTemplating/Mono.TextTemplating.Tests/TemplateEnginePreprocessTemplateTests.cs @@ -60,6 +60,16 @@ namespace Mono.TextTemplating.Tests Assert.AreEqual (expectedOutput, output, output); } + + [Test] + public void CaptureEncodingAndExtension () + { + string input = InputTemplate_CaptureEncodingAndExtension; + string output = Preprocess (input); + string expectedOutput = TemplatingEngineHelper.CleanCodeDom (Output_CaptureEncodingAndExtension, "\n"); + + Assert.AreEqual (expectedOutput, output, output); + } #region Helpers @@ -145,6 +155,12 @@ Included Method Body Text Block #> "; + public static string InputTemplate_CaptureEncodingAndExtension = + @" +<#@ template debug=""false"" language=""C#"" inherits=""Foo"" hostspecific=""trueFromBase"" #> +<#@ output extension="".cs"" encoding=""utf-8"" #> +"; + #endregion #region Expected output strings @@ -589,6 +605,34 @@ namespace Templating { } } "; + + public static string Output_CaptureEncodingAndExtension = + + @"namespace Templating { + + + public partial class PreprocessedTemplate : Foo { + + public override string TransformText() { + this.GenerationEnvironment = null; + + #line 1 """" + this.Write(""\n""); + + #line default + #line hidden + return this.GenerationEnvironment.ToString(); + } + + protected override void Initialize() { + if ((this.Host != null)) { + this.Host.SetFileExtension("".cs""); + this.Host.SetOutputEncoding(System.Text.Encoding.GetEncoding(65001, true)); + } + base.Initialize(); + } + } +}"; #endregion } } diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs index 409a36a9a6..f6a597752d 100644 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs +++ b/main/src/addins/TextTemplating/Mono.TextTemplating/Microsoft.VisualStudio.TextTemplating/TextTransformation.cs @@ -43,7 +43,7 @@ namespace Microsoft.VisualStudio.TextTemplating { } - protected internal virtual void Initialize () + public virtual void Initialize () { } @@ -55,15 +55,12 @@ namespace Microsoft.VisualStudio.TextTemplating public void Error (string message) { - Errors.Add (new CompilerError (null, -1, -1, null, message)); + Errors.Add (new CompilerError ("", 0, 0, "", message)); } public void Warning (string message) { - var err = new CompilerError (null, -1, -1, null, message) { - IsWarning = true, - }; - Errors.Add (err); + Errors.Add (new CompilerError ("", 0, 0, "", message) { IsWarning = true }); } protected internal CompilerErrorCollection Errors { diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs index 51934e42e3..8ef80cddc1 100644 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs +++ b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/RecyclableAppDomain.cs @@ -201,6 +201,12 @@ namespace Mono.TextTemplating {
map[name] = location;
}
+
+ //keep this alive as long as the app domain is alive
+ public override object InitializeLifetimeService ()
+ {
+ return null;
+ }
}
}
}
\ No newline at end of file diff --git a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs index 24394ff826..bdecf05e34 100644 --- a/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs +++ b/main/src/addins/TextTemplating/Mono.TextTemplating/Mono.TextTemplating/TemplatingEngine.cs @@ -500,7 +500,7 @@ namespace Mono.TextTemplating case SegmentType.Block: if (helperMode) //TODO: are blocks permitted after helpers? - throw new ParserException ("Blocks are not permitted after helpers", seg.StartLocation); + pt.LogError ("Blocks are not permitted after helpers", seg.TagStartLocation); st = new CodeSnippetStatement (seg.Text); break; case SegmentType.Expression: @@ -512,7 +512,8 @@ namespace Mono.TextTemplating st = new CodeExpressionStatement (new CodeMethodInvokeExpression (writeMeth, new CodePrimitiveExpression (seg.Text))); break; case SegmentType.Helper: - type.Members.Add (CreateSnippetMember (seg.Text, location)); + if (!string.IsNullOrEmpty (seg.Text)) + type.Members.Add (CreateSnippetMember (seg.Text, location)); helperMode = true; break; default: @@ -524,7 +525,9 @@ namespace Mono.TextTemplating //TODO: is there a way to do this for languages that use indentation for blocks, e.g. python? using (var writer = new StringWriter ()) { settings.Provider.GenerateCodeFromStatement (st, writer, null); - type.Members.Add (CreateSnippetMember (writer.ToString (), location )); + var text = writer.ToString (); + if (!string.IsNullOrEmpty (text)) + type.Members.Add (CreateSnippetMember (text, location)); } } else { st.LinePragma = location; @@ -546,7 +549,7 @@ namespace Mono.TextTemplating //class code and attributes from processors foreach (var processor in settings.DirectiveProcessors.Values) { string classCode = processor.GetClassCodeForProcessingRun (); - if (classCode != null) + if (!string.IsNullOrEmpty (classCode)) type.Members.Add (CreateSnippetMember (classCode)); var atts = processor.GetTemplateClassCustomAttributes (); if (atts != null) { @@ -605,6 +608,44 @@ namespace Mono.TextTemplating }; if (!settings.IncludePreprocessingHelpers) initializeMeth.Attributes |= MemberAttributes.Override; + + //if preprocessed, pass the extension and encoding to the host + if (settings.IsPreprocessed && settings.HostSpecific) { + var hostProp = new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Host"); + var statements = new List<CodeStatement> (); + + if (!string.IsNullOrEmpty (settings.Extension)) { + statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression ( + hostProp, + "SetFileExtension", + new CodePrimitiveExpression (settings.Extension) + ))); + } + + if (settings.Encoding != null) { + statements.Add (new CodeExpressionStatement (new CodeMethodInvokeExpression ( + hostProp, + "SetOutputEncoding", + new CodeMethodInvokeExpression( + new CodeTypeReferenceExpression (typeof(Encoding)), + "GetEncoding", + new CodePrimitiveExpression (settings.Encoding.CodePage), + new CodePrimitiveExpression(true) + ) + ))); + } + + if (statements.Count > 0) { + initializeMeth.Statements.Add (new CodeConditionStatement ( + new CodeBinaryOperatorExpression ( + hostProp, + CodeBinaryOperatorType.IdentityInequality, + new CodePrimitiveExpression (null) + ), + statements.ToArray() + )); + } + } //pre-init code from processors foreach (var processor in settings.DirectiveProcessors.Values) { diff --git a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFileGenerator.cs b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFileGenerator.cs index ce0582208c..5b37d5c0b2 100644 --- a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFileGenerator.cs +++ b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFileGenerator.cs @@ -28,14 +28,15 @@ using System; using MonoDevelop.Ide.CustomTools; using MonoDevelop.Projects; using MonoDevelop.Core; +using System.Threading.Tasks; namespace MonoDevelop.TextTemplating { public class TextTemplatingFileGenerator : ISingleFileCustomTool { - public IAsyncOperation Generate (IProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) + public Task Generate (ProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) { - return new ThreadAsyncOperation (delegate { + return Task.Factory.StartNew (delegate { using (var host = new ProjectFileTemplatingHost (file)) { host.AddMonoDevelopHostImport (); var defaultOutputName = file.FilePath.ChangeExtension (".cs"); //cs extension for VS compat @@ -50,7 +51,7 @@ namespace MonoDevelop.TextTemplating foreach (var err in host.Errors) monitor.Log.WriteLine (err); } - }, result); + }); } } } diff --git a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFilePreprocessor.cs b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFilePreprocessor.cs index bf08fb5dff..e1887f35b2 100644 --- a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFilePreprocessor.cs +++ b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingFilePreprocessor.cs @@ -33,14 +33,15 @@ using MonoDevelop.Ide; using MonoDevelop.Ide.CustomTools; using MonoDevelop.Projects; using MonoDevelop.Projects.Policies; +using System.Threading.Tasks; namespace MonoDevelop.TextTemplating { public class TextTemplatingFilePreprocessor : ISingleFileCustomTool { - public IAsyncOperation Generate (IProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) + public Task Generate (ProgressMonitor monitor, ProjectFile file, SingleFileCustomToolResult result) { - return new ThreadAsyncOperation (delegate { + return Task.Factory.StartNew (delegate { var host = new ProjectFileTemplatingHost (file); var dnp = file.Project as DotNetProject; @@ -74,7 +75,7 @@ namespace MonoDevelop.TextTemplating result.Errors.AddRange (host.Errors); foreach (var err in host.Errors) monitor.Log.WriteLine (err); - }, result); + }); } static bool warningLogged; diff --git a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingService.cs b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingService.cs index e434450482..34892038ad 100644 --- a/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingService.cs +++ b/main/src/addins/TextTemplating/MonoDevelop.TextTemplating/TextTemplatingService.cs @@ -39,7 +39,7 @@ namespace MonoDevelop.TextTemplating TaskService.Errors.Clear (); foreach (CompilerError err in errors) { - TaskService.Errors.Add (new Task (err.FileName, err.ErrorText, err.Column, err.Line, + TaskService.Errors.Add (new UserTask (err.FileName, err.ErrorText, err.Column, err.Line, err.IsWarning? TaskSeverity.Warning : TaskSeverity.Error)); } TaskService.ShowErrors (); diff --git a/main/src/addins/VBNetBinding/Gui/ProjectOptionsPanelWidget.cs b/main/src/addins/VBNetBinding/Gui/ProjectOptionsPanelWidget.cs index 211b6a8f7a..b72279305b 100644 --- a/main/src/addins/VBNetBinding/Gui/ProjectOptionsPanelWidget.cs +++ b/main/src/addins/VBNetBinding/Gui/ProjectOptionsPanelWidget.cs @@ -39,7 +39,7 @@ namespace MonoDevelop.VBNetBinding public partial class ProjectOptionsPanelWidget : Gtk.Bin { DotNetProject project; - VBProjectParameters parameters; + VBProjectExtension parameters; public ProjectOptionsPanelWidget (MonoDevelop.Projects.Project project) { @@ -49,7 +49,7 @@ namespace MonoDevelop.VBNetBinding this.Build(); this.project = (DotNetProject) project; - parameters = (VBProjectParameters) this.project.LanguageParameters; + parameters = this.project.GetService<VBProjectExtension> (); cr = new Gtk.CellRendererText (); store = new Gtk.ListStore (typeof (string)); diff --git a/main/src/addins/VBNetBinding/Project/Import.cs b/main/src/addins/VBNetBinding/Project/Import.cs index f8685402fa..227b7a27a1 100644 --- a/main/src/addins/VBNetBinding/Project/Import.cs +++ b/main/src/addins/VBNetBinding/Project/Import.cs @@ -30,14 +30,14 @@ using MonoDevelop.Projects; namespace MonoDevelop.VBNetBinding { - [DataItem ("Import")] - public class Import: SimpleProjectItem + public class Import: ProjectItem { public Import () { + ItemName = "Import"; } - public Import (string include) + public Import (string include): this () { Include = include; } diff --git a/main/src/addins/VBNetBinding/Project/VBCompilerParameters.cs b/main/src/addins/VBNetBinding/Project/VBCompilerParameters.cs index 386f8cab79..1dc141c777 100644 --- a/main/src/addins/VBNetBinding/Project/VBCompilerParameters.cs +++ b/main/src/addins/VBNetBinding/Project/VBCompilerParameters.cs @@ -36,7 +36,7 @@ using MonoDevelop.Core.Serialization; namespace MonoDevelop.VBNetBinding {
- public class VBCompilerParameters: ConfigurationParameters
+ public class VBCompilerParameters: DotNetCompilerParameters
{ // // Project level properties: diff --git a/main/src/addins/VBNetBinding/Project/VBProjectParameters.cs b/main/src/addins/VBNetBinding/Project/VBProjectExtension.cs index f3e8dd95ff..b10b0d0300 100644 --- a/main/src/addins/VBNetBinding/Project/VBProjectParameters.cs +++ b/main/src/addins/VBNetBinding/Project/VBProjectExtension.cs @@ -1,21 +1,21 @@ -// -// VBProjectParameters.cs -// +// +// VBProjectExtension.cs +// // Author: -// Lluis Sanchez Gual <lluis@novell.com> -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// +// Lluis Sanchez Gual <lluis@xamarin.com> +// +// Copyright (c) 2014 Xamarin, Inc (http://www.xamarin.com) +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,54 +23,44 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. - using System; -using MonoDevelop.Core.Serialization; using MonoDevelop.Projects; +using MonoDevelop.Projects.Formats.MSBuild; +using MonoDevelop.Core.Serialization; namespace MonoDevelop.VBNetBinding { - public class VBProjectParameters: DotNetProjectParameters + public class VBProjectExtension: DotNetProjectExtension { - public override bool DefaultNamespaceIsImplicit { - get { - return true; - } - } - [ItemProperty ("OptionInfer", DefaultValue="Off")] string optionInfer = "Off"; - + [ItemProperty ("OptionExplicit", DefaultValue="On")] string optionExplicit = "On"; - + [ItemProperty ("OptionCompare", DefaultValue="Binary")] string optionCompare = "Binary"; - + [ItemProperty ("OptionStrict", DefaultValue="Off")] string optionStrict = "Off"; - + [ItemProperty ("MyType", DefaultValue="")] string myType = string.Empty; - + [ItemProperty ("StartupObject", DefaultValue="")] string startupObject = string.Empty; - + [ProjectPathItemProperty ("ApplicationIcon", DefaultValue="")] string applicationIcon = string.Empty; - + [ItemProperty ("CodePage", DefaultValue="")] string codePage = string.Empty; - - public VBProjectParameters() - { - } - + public bool OptionInfer { get { return optionInfer == "On"; } set { optionInfer = value ? "On" : "Off"; } } - + public bool OptionExplicit { get { return optionExplicit == "On"; } set { optionExplicit = value ? "On" : "Off"; } @@ -85,25 +75,44 @@ namespace MonoDevelop.VBNetBinding get { return optionStrict == "On"; } set { optionStrict = value ? "On" : "Off"; } } - + public string MyType { get { return myType; } set { myType = value ?? string.Empty; } } - + public string StartupObject { get { return startupObject; } set { startupObject = value ?? string.Empty; } } - + public string ApplicationIcon { get { return applicationIcon; } set { applicationIcon = value ?? string.Empty; } } - + public string CodePage { get { return codePage; } set { codePage = value ?? string.Empty; } } + + protected override void Initialize () + { + base.Initialize (); + Project.DefaultNamespaceIsImplicit = true; + } + + protected override void OnReadProject (MonoDevelop.Core.ProgressMonitor monitor, MSBuildProject msproject) + { + base.OnReadProject (monitor, msproject); + msproject.GetGlobalPropertyGroup ().ReadObjectProperties (this, typeof(VBProjectExtension)); + } + + protected override void OnWriteProject (MonoDevelop.Core.ProgressMonitor monitor, MSBuildProject msproject) + { + base.OnWriteProject (monitor, msproject); + msproject.GetGlobalPropertyGroup ().WriteObjectProperties (this, typeof(VBProjectExtension)); + } } } + diff --git a/main/src/addins/VBNetBinding/VBBindingCompilerServices.cs b/main/src/addins/VBNetBinding/VBBindingCompilerServices.cs index a5eb348271..8ef14e9669 100644 --- a/main/src/addins/VBNetBinding/VBBindingCompilerServices.cs +++ b/main/src/addins/VBNetBinding/VBBindingCompilerServices.cs @@ -55,7 +55,7 @@ namespace MonoDevelop.VBNetBinding { static Regex regexError = new Regex (@"^\s*((?<file>.*)\s?\((?<line>\d*)(,(?<column>\d*))?\) : )?(?<level>\w+) :? ?(?<number>[^:]*): (?<message>.*)$", RegexOptions.Compiled | RegexOptions.ExplicitCapture); - string GenerateOptions (DotNetProjectConfiguration configuration, VBCompilerParameters compilerparameters, VBProjectParameters projectparameters, string outputFileName) + string GenerateOptions (DotNetProjectConfiguration configuration, VBCompilerParameters compilerparameters, VBProjectExtension projectparameters, string outputFileName) { DotNetProject project = (DotNetProject) configuration.ParentItem; StringBuilder sb = new StringBuilder (); @@ -189,16 +189,14 @@ namespace MonoDevelop.VBNetBinding { return sb.ToString(); } - public BuildResult Compile (ProjectItemCollection items, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) + public BuildResult Compile (ProjectItemCollection items, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor) { VBCompilerParameters compilerparameters = (VBCompilerParameters) configuration.CompilationParameters; if (compilerparameters == null) compilerparameters = new VBCompilerParameters (); - VBProjectParameters projectparameters = (VBProjectParameters) configuration.ProjectParameters; - if (projectparameters == null) - projectparameters = new VBProjectParameters (); - + var projectparameters = configuration.ParentItem.GetService<VBProjectExtension> (); + string exe = configuration.CompiledOutputName; string responseFileName = Path.GetTempFileName(); StreamWriter writer = new StreamWriter (responseFileName); diff --git a/main/src/addins/VBNetBinding/VBLanguageBinding.cs b/main/src/addins/VBNetBinding/VBLanguageBinding.cs index 0fbca6123c..8ddde46aaa 100644 --- a/main/src/addins/VBNetBinding/VBLanguageBinding.cs +++ b/main/src/addins/VBNetBinding/VBLanguageBinding.cs @@ -62,13 +62,13 @@ namespace MonoDevelop.VBNetBinding return Path.GetExtension(fileName) == ".vb"; } - public BuildResult Compile (ProjectItemCollection items, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) + public BuildResult Compile (ProjectItemCollection items, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor) { Debug.Assert(compilerServices != null); return compilerServices.Compile (items, configuration, configSelector, monitor); } - public ConfigurationParameters CreateCompilationParameters (XmlElement projectOptions) + public DotNetCompilerParameters CreateCompilationParameters (XmlElement projectOptions) { return new VBCompilerParameters (); } @@ -94,11 +94,6 @@ namespace MonoDevelop.VBNetBinding return new ClrVersion[] { ClrVersion.Net_2_0, ClrVersion.Net_4_0 }; } - public ProjectParameters CreateProjectParameters (XmlElement projectOptions) - { - return new VBProjectParameters (); - } - class ImprovedCodeDomProvider : Microsoft.VisualBasic.VBCodeProvider { [Obsolete ("Use CodeDomProvider class")] diff --git a/main/src/addins/VBNetBinding/VBNetBinding.csproj b/main/src/addins/VBNetBinding/VBNetBinding.csproj index d730d2a3f5..7591c7b96c 100644 --- a/main/src/addins/VBNetBinding/VBNetBinding.csproj +++ b/main/src/addins/VBNetBinding/VBNetBinding.csproj @@ -95,8 +95,8 @@ <Compile Include="Gui\ImportsOptionsPanelWidget.cs" /> <Compile Include="Gui\ImportsOptionsPanel.cs" /> <Compile Include="gtk-gui\MonoDevelop.VBNetBinding.ImportsOptionsPanelWidget.cs" /> - <Compile Include="Project\VBProjectParameters.cs" /> <Compile Include="AddinInfo.cs" /> + <Compile Include="Project\VBProjectExtension.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="templates\EmptyVBFile.xft.xml"> diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseGitRepositoryTests.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseGitRepositoryTests.cs index 8841f269d3..a87f73024f 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseGitRepositoryTests.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseGitRepositoryTests.cs @@ -155,7 +155,7 @@ namespace MonoDevelop.VersionControl.Git.Tests protected override void PostCommit (Repository repo)
{
var repo2 = (GitRepository)repo;
- repo2.Push (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), repo2.GetCurrentRemote (), repo2.GetCurrentBranch ());
+ repo2.Push (new MonoDevelop.Core.ProgressMonitor (), repo2.GetCurrentRemote (), repo2.GetCurrentBranch ());
}
protected override void BlameExtraInternals (Annotation [] annotations)
@@ -193,19 +193,19 @@ namespace MonoDevelop.VersionControl.Git.Tests AddFile ("file1", "text", true, true);
repo2.CreateBranch ("branch1", null);
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "branch1");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "branch1");
Assert.AreEqual ("branch1", repo2.GetCurrentBranch ());
Assert.IsTrue (File.Exists (LocalPath + "file1"), "Branch not inheriting from current.");
AddFile ("file2", "text", true, false);
repo2.CreateBranch ("branch2", null);
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "branch2");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "branch2");
Assert.IsTrue (!File.Exists (LocalPath + "file2"), "Uncommitted changes were not stashed");
repo2.GetStashes ().Pop (new NullProgressMonitor ());
Assert.IsTrue (File.Exists (LocalPath + "file2"), "Uncommitted changes were not stashed correctly");
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "master");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "master");
repo2.RemoveBranch ("branch1");
Assert.IsFalse (repo2.GetBranches ().Any (b => b.Name == "branch1"), "Failed to delete branch");
@@ -224,14 +224,14 @@ namespace MonoDevelop.VersionControl.Git.Tests PostCommit (repo2);
repo2.CreateBranch ("branch3", null);
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "branch3");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "branch3");
AddFile ("file2", "asdf", true, true);
- repo2.Push (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "origin", "branch3");
+ repo2.Push (new MonoDevelop.Core.ProgressMonitor (), "origin", "branch3");
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "master");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "master");
repo2.CreateBranch ("branch4", "origin/branch3");
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "branch4");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "branch4");
Assert.IsTrue (File.Exists (LocalPath + "file2"), "Tracking remote is not grabbing correct commits");
}
@@ -306,7 +306,7 @@ namespace MonoDevelop.VersionControl.Git.Tests AddFile ("file1", "text", true, true);
PostCommit (repo2);
repo2.CreateBranch ("branch1", null);
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "branch1");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "branch1");
AddFile ("file2", "text", true, true);
PostCommit (repo2);
Assert.AreEqual (2, repo2.GetBranches ().Count ());
@@ -329,12 +329,12 @@ namespace MonoDevelop.VersionControl.Git.Tests Assert.IsTrue (repo2.IsBranchMerged ("master"));
repo2.CreateBranch ("branch1", null);
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "branch1");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "branch1");
AddFile ("file2", "text", true, true);
- repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (), "master");
+ repo2.SwitchToBranch (new MonoDevelop.Core.ProgressMonitor (), "master");
Assert.IsFalse (repo2.IsBranchMerged ("branch1"));
- repo2.Merge ("branch1", GitUpdateOptions.NormalUpdate, new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor ());
+ repo2.Merge ("branch1", GitUpdateOptions.NormalUpdate, new MonoDevelop.Core.ProgressMonitor ());
Assert.IsTrue (repo2.IsBranchMerged ("branch1"));
}
diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseRepositoryTests.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseRepositoryTests.cs index ba74fd3e0e..648cc45fdb 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseRepositoryTests.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git.Tests/BaseRepositoryTests.cs @@ -242,15 +242,15 @@ namespace MonoDevelop.VersionControl.Tests Repo2 = GetRepo (second, RemoteUrl); string added = second + "testfile2"; File.Create (added).Close (); - Repo2.Add (added, false, new NullProgressMonitor ()); + Repo2.Add (added, false, new ProgressMonitor ()); ChangeSet changes = Repo.CreateChangeSet (Repo.RootPath); changes.AddFile (Repo.GetVersionInfo (added, VersionInfoQueryFlags.IgnoreCache)); changes.GlobalComment = "test2"; - Repo2.Commit (changes, new NullProgressMonitor ()); + Repo2.Commit (changes, new ProgressMonitor ()); PostCommit (Repo2); - Repo.Update (Repo.RootPath, true, new NullProgressMonitor ()); + Repo.Update (Repo.RootPath, true, new ProgressMonitor ()); Assert.True (File.Exists (LocalPath + "testfile2")); DeleteDirectory (second); @@ -290,7 +290,7 @@ namespace MonoDevelop.VersionControl.Tests // Revert to head. File.WriteAllText (added, content); - Repo.Revert (added, false, new NullProgressMonitor ()); + Repo.Revert (added, false, new ProgressMonitor ()); Assert.AreEqual (Repo.GetBaseText (added), File.ReadAllText (added)); } @@ -317,7 +317,7 @@ namespace MonoDevelop.VersionControl.Tests string added = LocalPath + "testfile2"; AddFile ("testfile", "text", true, true); AddFile ("testfile2", "text2", true, true); - Repo.RevertRevision (added, GetHeadRevision (), new NullProgressMonitor ()); + Repo.RevertRevision (added, GetHeadRevision (), new ProgressMonitor ()); Assert.IsFalse (File.Exists (added)); } @@ -334,7 +334,7 @@ namespace MonoDevelop.VersionControl.Tests AddFile ("testfile", null, true, true); src = LocalPath + "testfile"; dst = src + "2"; - Repo.MoveFile (src, dst, false, new NullProgressMonitor ()); + Repo.MoveFile (src, dst, false, new ProgressMonitor ()); srcVi = Repo.GetVersionInfo (src, VersionInfoQueryFlags.IgnoreCache); dstVi = Repo.GetVersionInfo (dst, VersionInfoQueryFlags.IgnoreCache); const VersionStatus versionedStatus = VersionStatus.ScheduledDelete | VersionStatus.ScheduledReplace; @@ -345,7 +345,7 @@ namespace MonoDevelop.VersionControl.Tests AddFile ("addedfile", null, true, false); src = LocalPath + "addedfile"; dst = src + "2"; - Repo.MoveFile (src, dst, false, new NullProgressMonitor ()); + Repo.MoveFile (src, dst, false, new ProgressMonitor ()); srcVi = Repo.GetVersionInfo (src, VersionInfoQueryFlags.IgnoreCache); dstVi = Repo.GetVersionInfo (dst, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.Unversioned, srcVi.Status); @@ -355,7 +355,7 @@ namespace MonoDevelop.VersionControl.Tests AddFile ("unversionedfile", null, false, false); src = LocalPath + "unversionedfile"; dst = src + "2"; - Repo.MoveFile (src, dst, false, new NullProgressMonitor ()); + Repo.MoveFile (src, dst, false, new ProgressMonitor ()); srcVi = Repo.GetVersionInfo (src, VersionInfoQueryFlags.IgnoreCache); dstVi = Repo.GetVersionInfo (dst, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.Unversioned, srcVi.Status); @@ -374,7 +374,7 @@ namespace MonoDevelop.VersionControl.Tests AddDirectory ("test", true, false); AddFile ("test" + Path.DirectorySeparatorChar + "testfile", null, true, true); - Repo.MoveDirectory (srcDir, dstDir, false, new NullProgressMonitor ()); + Repo.MoveDirectory (srcDir, dstDir, false, new ProgressMonitor ()); VersionInfo srcVi = Repo.GetVersionInfo (src, VersionInfoQueryFlags.IgnoreCache); VersionInfo dstVi = Repo.GetVersionInfo (dst, VersionInfoQueryFlags.IgnoreCache); const VersionStatus expectedStatus = VersionStatus.ScheduledDelete | VersionStatus.ScheduledReplace; @@ -390,7 +390,7 @@ namespace MonoDevelop.VersionControl.Tests // Versioned file. added = LocalPath + "testfile1" + postFix; AddFile ("testfile1" + postFix, null, true, true); - Repo.DeleteFile (added, true, new NullProgressMonitor (), keepLocal); + Repo.DeleteFile (added, true, new ProgressMonitor (), keepLocal); vi = Repo.GetVersionInfo (added, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.ScheduledDelete, vi.Status & VersionStatus.ScheduledDelete); Assert.AreEqual (keepLocal, File.Exists (added)); @@ -398,7 +398,7 @@ namespace MonoDevelop.VersionControl.Tests // Just added file. added = LocalPath + "testfile2" + postFix; AddFile ("testfile2" + postFix, null, true, false); - Repo.DeleteFile (added, true, new NullProgressMonitor (), keepLocal); + Repo.DeleteFile (added, true, new ProgressMonitor (), keepLocal); vi = Repo.GetVersionInfo (added, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.Unversioned, vi.Status); Assert.AreEqual (keepLocal, File.Exists (added)); @@ -406,7 +406,7 @@ namespace MonoDevelop.VersionControl.Tests // Non versioned file. added = LocalPath + "testfile3" + postFix; AddFile ("testfile3" + postFix, null, false, false); - Repo.DeleteFile (added, true, new NullProgressMonitor (), keepLocal); + Repo.DeleteFile (added, true, new ProgressMonitor (), keepLocal); vi = Repo.GetVersionInfo (added, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.Unversioned, vi.Status); Assert.AreEqual (keepLocal, File.Exists (added)); @@ -433,7 +433,7 @@ namespace MonoDevelop.VersionControl.Tests AddDirectory ("test1" + postFix, true, false); AddFile ("test1" + postFix + Path.DirectorySeparatorChar + "testfile", null, true, true); - Repo.DeleteDirectory (addedDir, true, new NullProgressMonitor (), keepLocal); + Repo.DeleteDirectory (addedDir, true, new ProgressMonitor (), keepLocal); vi = Repo.GetVersionInfo (added, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.ScheduledDelete, vi.Status & VersionStatus.ScheduledDelete); Assert.AreEqual (keepLocal, File.Exists (added)); @@ -444,7 +444,7 @@ namespace MonoDevelop.VersionControl.Tests AddDirectory ("test2" + postFix, true, false); AddFile ("test2" + postFix + Path.DirectorySeparatorChar + "testfile", null, true, false); - Repo.DeleteDirectory (addedDir, true, new NullProgressMonitor (), keepLocal); + Repo.DeleteDirectory (addedDir, true, new ProgressMonitor (), keepLocal); vi = Repo.GetVersionInfo (added, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.Unversioned, vi.Status); Assert.AreEqual (keepLocal, File.Exists (added)); @@ -455,7 +455,7 @@ namespace MonoDevelop.VersionControl.Tests AddDirectory ("test3" + postFix, true, false); AddFile ("test3" + postFix + Path.DirectorySeparatorChar + "testfile", null, false, false); - Repo.DeleteDirectory (addedDir, true, new NullProgressMonitor (), keepLocal); + Repo.DeleteDirectory (addedDir, true, new ProgressMonitor (), keepLocal); vi = Repo.GetVersionInfo (added, VersionInfoQueryFlags.IgnoreCache); Assert.AreEqual (VersionStatus.Unversioned, vi.Status); Assert.AreEqual (keepLocal, File.Exists (added)); @@ -475,7 +475,7 @@ namespace MonoDevelop.VersionControl.Tests { string added = LocalPath + "testfile"; AddFile ("testfile", null, true, true); - Repo.Lock (new NullProgressMonitor (), added); + Repo.Lock (new ProgressMonitor (), added); PostLock (); } @@ -490,8 +490,8 @@ namespace MonoDevelop.VersionControl.Tests { string added = LocalPath + "testfile"; AddFile ("testfile", null, true, true); - Repo.Lock (new NullProgressMonitor (), "testfile"); - Repo.Unlock (new NullProgressMonitor (), added); + Repo.Lock (new ProgressMonitor (), "testfile"); + Repo.Unlock (new ProgressMonitor (), added); PostLock (); } @@ -575,7 +575,7 @@ namespace MonoDevelop.VersionControl.Tests protected void Checkout (string path, string url) { Repository _repo = GetRepo (path, url); - _repo.Checkout (path, true, new NullProgressMonitor ()); + _repo.Checkout (path, true, new ProgressMonitor ()); if (Repo == null) Repo = _repo; else @@ -589,7 +589,7 @@ namespace MonoDevelop.VersionControl.Tests changes.AddFile (Repo.GetVersionInfo (item, VersionInfoQueryFlags.IgnoreCache)); } changes.GlobalComment = String.Format ("Commit #{0}", CommitNumber); - Repo.Commit (changes, new NullProgressMonitor ()); + Repo.Commit (changes, new ProgressMonitor ()); CommitNumber++; } @@ -603,7 +603,7 @@ namespace MonoDevelop.VersionControl.Tests changes.AddFile (Repo.GetVersionInfo (path, VersionInfoQueryFlags.IgnoreCache)); changes.GlobalComment = String.Format ("Commit #{0}", CommitNumber); - Repo.Commit (changes, new NullProgressMonitor ()); + Repo.Commit (changes, new ProgressMonitor ()); CommitNumber++; } @@ -626,7 +626,7 @@ namespace MonoDevelop.VersionControl.Tests File.WriteAllText (added, contents); if (toVcs) - Repo.Add (added, false, new NullProgressMonitor ()); + Repo.Add (added, false, new ProgressMonitor ()); if (commit) CommitFile (added); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs index b624b70f0e..72d67d950a 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs @@ -50,7 +50,7 @@ namespace MonoDevelop.VersionControl.Git { public GitRepository Repository { get { - IWorkspaceObject wob = IdeApp.ProjectOperations.CurrentSelectedSolutionItem; + WorkspaceObject wob = IdeApp.ProjectOperations.CurrentSelectedSolutionItem; if (wob == null) wob = IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem; if (wob != null) @@ -86,7 +86,7 @@ namespace MonoDevelop.VersionControl.Git if (repo == null) return; - IWorkspaceObject wob = IdeApp.ProjectOperations.CurrentSelectedItem as IWorkspaceObject; + WorkspaceObject wob = IdeApp.ProjectOperations.CurrentSelectedItem as WorkspaceObject; if (wob == null) return; if (((wob is WorkspaceItem) && ((WorkspaceItem)wob).ParentWorkspace == null) || diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs index 6f008faa03..03561045fe 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs @@ -35,7 +35,7 @@ namespace MonoDevelop.VersionControl.Git { sealed class GitNodeBuilderExtension: NodeBuilderExtension { - readonly Dictionary<FilePath,IWorkspaceObject> repos = new Dictionary<FilePath, IWorkspaceObject> (); + readonly Dictionary<FilePath,WorkspaceObject> repos = new Dictionary<FilePath, WorkspaceObject> (); protected override void Initialize () { @@ -53,15 +53,15 @@ namespace MonoDevelop.VersionControl.Git public override bool CanBuildNode (Type dataType) { - return typeof(IWorkspaceObject).IsAssignableFrom (dataType); + return typeof(WorkspaceObject).IsAssignableFrom (dataType); } public override void BuildNode (ITreeBuilder treeBuilder, object dataObject, NodeInfo nodeInfo) { - IWorkspaceObject ob = (IWorkspaceObject) dataObject; + WorkspaceObject ob = (WorkspaceObject) dataObject; GitRepository rep = VersionControlService.GetRepository (ob) as GitRepository; if (rep != null) { - IWorkspaceObject rob; + WorkspaceObject rob; if (repos.TryGetValue (rep.RootPath.CanonicalPath, out rob)) { if (ob == rob) nodeInfo.Label += " (" + rep.GetCurrentBranch () + ")"; @@ -71,7 +71,7 @@ namespace MonoDevelop.VersionControl.Git public override void OnNodeAdded (object dataObject) { - IWorkspaceObject ob = (IWorkspaceObject) dataObject; + WorkspaceObject ob = (WorkspaceObject) dataObject; GitRepository rep = VersionControlService.GetRepository (ob) as GitRepository; if (rep != null && !repos.ContainsKey (rep.RootPath.CanonicalPath)) { repos [rep.RootPath] = ob; @@ -80,9 +80,9 @@ namespace MonoDevelop.VersionControl.Git public override void OnNodeRemoved (object dataObject) { - IWorkspaceObject ob = (IWorkspaceObject) dataObject; + WorkspaceObject ob = (WorkspaceObject) dataObject; GitRepository rep = VersionControlService.GetRepository (ob) as GitRepository; - IWorkspaceObject rob; + WorkspaceObject rob; if (rep != null && repos.TryGetValue (rep.RootPath.CanonicalPath, out rob)) { if (ob == rob) repos.Remove (rep.RootPath.CanonicalPath); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs index 144e81b7ce..83725fb1d1 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs @@ -44,6 +44,7 @@ using NGit.Transport; using NGit.Diff; using NGit.Merge; using NGit.Submodule; +using ProgressMonitor = MonoDevelop.Core.ProgressMonitor; namespace MonoDevelop.VersionControl.Git { @@ -409,7 +410,7 @@ namespace MonoDevelop.VersionControl.Git .Select (f => new FilePath (f).CanonicalPath)); } - protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, IProgressMonitor monitor) + protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, ProgressMonitor monitor) { // Initialize the repository RootRepository = GitUtil.Init (localPath, Url); @@ -451,7 +452,7 @@ namespace MonoDevelop.VersionControl.Git return this; } - protected override void OnUpdate (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) + protected override void OnUpdate (FilePath[] localPaths, bool recurse, ProgressMonitor monitor) { IEnumerable<DiffEntry> statusList = null; @@ -478,7 +479,7 @@ namespace MonoDevelop.VersionControl.Git monitor.EndTask (); } - public void Fetch (IProgressMonitor monitor) + public void Fetch (ProgressMonitor monitor) { string remote = GetCurrentRemote (); if (remote == null) @@ -536,7 +537,7 @@ namespace MonoDevelop.VersionControl.Git return true; } - public void Rebase (string upstreamRef, GitUpdateOptions options, IProgressMonitor monitor) + public void Rebase (string upstreamRef, GitUpdateOptions options, ProgressMonitor monitor) { StashCollection stashes = GitUtil.GetStashes (RootRepository); Stash stash = null; @@ -660,7 +661,7 @@ namespace MonoDevelop.VersionControl.Git } } - public void Merge (string branch, GitUpdateOptions options, IProgressMonitor monitor) + public void Merge (string branch, GitUpdateOptions options, ProgressMonitor monitor) { IEnumerable<DiffEntry> statusList = null; Stash stash = null; @@ -798,7 +799,7 @@ namespace MonoDevelop.VersionControl.Git return res; } - protected override void OnCommit (ChangeSet changeSet, IProgressMonitor monitor) + protected override void OnCommit (ChangeSet changeSet, ProgressMonitor monitor) { string message = changeSet.GlobalComment; if (string.IsNullOrEmpty (message)) @@ -864,7 +865,7 @@ namespace MonoDevelop.VersionControl.Git config.Save (); } - protected override void OnCheckout (FilePath targetLocalPath, Revision rev, bool recurse, IProgressMonitor monitor) + protected override void OnCheckout (FilePath targetLocalPath, Revision rev, bool recurse, ProgressMonitor monitor) { CloneCommand cmd = NGit.Api.Git.CloneRepository (); cmd.SetURI (Url); @@ -889,108 +890,109 @@ namespace MonoDevelop.VersionControl.Git } } - protected override void OnRevert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) + protected override void OnRevert (FilePath[] localPaths, bool recurse, ProgressMonitor monitor) { // Replace with NGit.Api.Git.Reset () + // FIXME: we lack info about what happened to files - foreach (var group in GroupByRepository (localPaths)) { + + var groups = GroupByRepository (localPaths).ToArray (); + monitor.BeginTask (GettextCatalog.GetString ("Reverting files"), groups.Length); + + foreach (var group in groups) { + monitor.BeginStep (1); var repository = group.Key; var files = group.ToArray (); - var c = GetHeadCommit (repository); - RevTree tree = c != null ? c.Tree : null; - - List<FilePath> changedFiles = new List<FilePath> (); - List<FilePath> removedFiles = new List<FilePath> (); - - monitor.BeginTask (GettextCatalog.GetString ("Reverting files"), 3); - monitor.BeginStepTask (GettextCatalog.GetString ("Reverting files"), files.Length, 2); - - DirCache dc = repository.LockDirCache (); - DirCacheBuilder builder = dc.Builder (); - - try { - HashSet<string> entriesToRemove = new HashSet<string> (); - HashSet<string> foldersToRemove = new HashSet<string> (); + var c = GetHeadCommit (repository); + RevTree tree = c != null ? c.Tree : null; - // Add the new entries - foreach (FilePath fp in files) { - string p = repository.ToGitPath (fp); - - // Register entries to be removed from the index - if (Directory.Exists (fp)) - foldersToRemove.Add (p); - else - entriesToRemove.Add (p); + List<FilePath> changedFiles = new List<FilePath> (); + List<FilePath> removedFiles = new List<FilePath> (); + + monitor.BeginTask (files.Length); + + DirCache dc = repository.LockDirCache (); + DirCacheBuilder builder = dc.Builder (); + + try { + HashSet<string> entriesToRemove = new HashSet<string> (); + HashSet<string> foldersToRemove = new HashSet<string> (); - TreeWalk tw = tree != null ? TreeWalk.ForPath (repository, p, tree) : null; - if (tw == null) { - // Removed from the index - } - else { - // Add new entries + // Add the new entries + foreach (FilePath fp in files) { + string p = repository.ToGitPath (fp); - TreeWalk r; - if (tw.IsSubtree) { - // It's a directory. Make sure we remove existing index entries of this directory + // Register entries to be removed from the index + if (Directory.Exists (fp)) foldersToRemove.Add (p); + else + entriesToRemove.Add (p); + + TreeWalk tw = tree != null ? TreeWalk.ForPath (repository, p, tree) : null; + if (tw == null) { + // Removed from the index + } + else { + // Add new entries - // We have to iterate through all folder files. We need a new iterator since the - // existing rw is not recursive - r = new TreeWalk(repository); - r.Reset (tree); - r.Filter = PathFilterGroup.CreateFromStrings(new string[]{p}); - r.Recursive = true; - r.Next (); - } else { - r = tw; + TreeWalk r; + if (tw.IsSubtree) { + // It's a directory. Make sure we remove existing index entries of this directory + foldersToRemove.Add (p); + + // We have to iterate through all folder files. We need a new iterator since the + // existing rw is not recursive + r = new TreeWalk(repository); + r.Reset (tree); + r.Filter = PathFilterGroup.CreateFromStrings(new string[]{p}); + r.Recursive = true; + r.Next (); + } else { + r = tw; + } + + do { + // There can be more than one entry if reverting a whole directory + string rpath = repository.FromGitPath (r.PathString); + DirCacheEntry e = new DirCacheEntry (r.PathString); + e.SetObjectId (r.GetObjectId (0)); + e.FileMode = r.GetFileMode (0); + if (!Directory.Exists (Path.GetDirectoryName (rpath))) + Directory.CreateDirectory (rpath); + DirCacheCheckout.CheckoutEntry (repository, rpath, e); + builder.Add (e); + changedFiles.Add (rpath); + } while (r.Next ()); } - - do { - // There can be more than one entry if reverting a whole directory - string rpath = repository.FromGitPath (r.PathString); - DirCacheEntry e = new DirCacheEntry (r.PathString); - e.SetObjectId (r.GetObjectId (0)); - e.FileMode = r.GetFileMode (0); - if (!Directory.Exists (Path.GetDirectoryName (rpath))) - Directory.CreateDirectory (rpath); - DirCacheCheckout.CheckoutEntry (repository, rpath, e); + } + + // Add entries we want to keep + int count = dc.GetEntryCount (); + for (int n=0; n<count; n++) { + DirCacheEntry e = dc.GetEntry (n); + string path = e.PathString; + if (!entriesToRemove.Contains (path) && !foldersToRemove.Any (f => IsSubpath (f,path))) builder.Add (e); - changedFiles.Add (rpath); - } while (r.Next ()); } + + builder.Commit (); monitor.Step (1); } - - // Add entries we want to keep - int count = dc.GetEntryCount (); - for (int n=0; n<count; n++) { - DirCacheEntry e = dc.GetEntry (n); - string path = e.PathString; - if (!entriesToRemove.Contains (path) && !foldersToRemove.Any (f => IsSubpath (f,path))) - builder.Add (e); + catch { + dc.Unlock (); + throw; } - builder.Commit (); - } - catch { - dc.Unlock (); - throw; - } - - monitor.EndTask (); - monitor.BeginTask (null, files.Length); + foreach (FilePath p in changedFiles) + FileService.NotifyFileChanged (p, true); - foreach (FilePath p in changedFiles) { - FileService.NotifyFileChanged (p, true); - monitor.Step (1); - } - foreach (FilePath p in removedFiles) { - FileService.NotifyFileRemoved (p); - monitor.Step (1); + foreach (FilePath p in removedFiles) + FileService.NotifyFileRemoved (p); + + monitor.EndTask (); } monitor.EndTask (); - } } static bool IsSubpath (string basePath, string childPath) @@ -1001,12 +1003,12 @@ namespace MonoDevelop.VersionControl.Git return childPath.StartsWith (basePath + "/", StringComparison.InvariantCulture); } - protected override void OnRevertRevision (FilePath localPath, Revision revision, IProgressMonitor monitor) + protected override void OnRevertRevision (FilePath localPath, Revision revision, ProgressMonitor monitor) { throw new NotSupportedException (); } - protected override void OnRevertToRevision (FilePath localPath, Revision revision, IProgressMonitor monitor) + protected override void OnRevertToRevision (FilePath localPath, Revision revision, ProgressMonitor monitor) { NGit.Repository repo = GetRepository (localPath); NGit.Api.Git git = new NGit.Api.Git (repo); @@ -1020,7 +1022,7 @@ namespace MonoDevelop.VersionControl.Git } - protected override void OnAdd (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) + protected override void OnAdd (FilePath[] localPaths, bool recurse, ProgressMonitor monitor) { foreach (var group in GroupByRepository (localPaths)) { var repository = group.Key; @@ -1034,7 +1036,7 @@ namespace MonoDevelop.VersionControl.Git } } - protected override void OnDeleteFiles (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal) + protected override void OnDeleteFiles (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal) { DeleteCore (localPaths, force, monitor, keepLocal); @@ -1054,7 +1056,7 @@ namespace MonoDevelop.VersionControl.Git } } - protected override void OnDeleteDirectories (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal) + protected override void OnDeleteDirectories (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal) { DeleteCore (localPaths, force, monitor, keepLocal); @@ -1076,7 +1078,7 @@ namespace MonoDevelop.VersionControl.Git } } - void DeleteCore (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal) + void DeleteCore (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal) { foreach (var group in GroupByRepository (localPaths)) { List<FilePath> backupFiles = new List<FilePath> (); @@ -1220,7 +1222,7 @@ namespace MonoDevelop.VersionControl.Git return remotes[0]; } - public void Push (IProgressMonitor monitor, string remote, string remoteBranch) + public void Push (ProgressMonitor monitor, string remote, string remoteBranch) { string remoteRef = "refs/heads/" + remoteBranch; IEnumerable<PushResult> res; @@ -1422,7 +1424,7 @@ namespace MonoDevelop.VersionControl.Git return RootRepository.GetBranch (); } - public void SwitchToBranch (IProgressMonitor monitor, string branch) + public void SwitchToBranch (ProgressMonitor monitor, string branch) { monitor.BeginTask (GettextCatalog.GetString ("Switching to branch {0}", branch), GitService.StashUnstashWhenSwitchingBranches ? 4 : 2); @@ -1477,7 +1479,7 @@ namespace MonoDevelop.VersionControl.Git monitor.EndTask (); } - void NotifyFileChanges (IProgressMonitor monitor, IEnumerable<DiffEntry> statusList) + void NotifyFileChanges (ProgressMonitor monitor, IEnumerable<DiffEntry> statusList) { List<DiffEntry> changes = new List<DiffEntry> (statusList); @@ -1575,7 +1577,7 @@ namespace MonoDevelop.VersionControl.Git return diffs.ToArray (); } - protected override void OnMoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) + protected override void OnMoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor) { VersionInfo vi = GetVersionInfo (localSrcPath, VersionInfoQueryFlags.IgnoreCache); if (vi == null || !vi.IsVersioned) { @@ -1589,7 +1591,7 @@ namespace MonoDevelop.VersionControl.Git Revert (localSrcPath, false, monitor); } - protected override void OnMoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) + protected override void OnMoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor) { VersionInfo[] versionedFiles = GetDirectoryVersionInfo (localSrcPath, false, true); base.OnMoveDirectory (localSrcPath, localDestPath, force, monitor); @@ -1767,21 +1769,21 @@ namespace MonoDevelop.VersionControl.Git public string PushUrl { get; internal set; } } - class GitMonitor: ProgressMonitor, IDisposable + class GitMonitor: NGit.ProgressMonitor, IDisposable { - readonly IProgressMonitor monitor; + readonly MonoDevelop.Core.ProgressMonitor monitor; int currentWork; int currentStep; bool taskStarted; int totalTasksOverride = -1; bool monitorStarted; - public GitMonitor (IProgressMonitor monitor) + public GitMonitor (MonoDevelop.Core.ProgressMonitor monitor) { this.monitor = monitor; } - public GitMonitor (IProgressMonitor monitor, int totalTasksOverride) + public GitMonitor (MonoDevelop.Core.ProgressMonitor monitor, int totalTasksOverride) { this.monitor = monitor; this.totalTasksOverride = totalTasksOverride; @@ -1829,7 +1831,7 @@ namespace MonoDevelop.VersionControl.Git public override bool IsCancelled () { - return monitor.IsCancelRequested; + return monitor.CancellationToken.IsCancellationRequested; } public void Dispose () diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitService.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitService.cs index 41ffac25fd..6b7d86cf14 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitService.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitService.cs @@ -30,6 +30,7 @@ using MonoDevelop.Ide; using MonoDevelop.Ide.ProgressMonitoring; using NGit.Api; using System.Threading; +using System.Threading.Tasks; namespace MonoDevelop.VersionControl.Git { @@ -63,7 +64,7 @@ namespace MonoDevelop.VersionControl.Git string remote = dlg.SelectedRemote; string branch = dlg.SelectedRemoteBranch ?? repo.GetCurrentBranch (); - IProgressMonitor monitor = VersionControlService.GetProgressMonitor (GettextCatalog.GetString ("Pushing changes..."), VersionControlOperationType.Push); + ProgressMonitor monitor = VersionControlService.GetProgressMonitor (GettextCatalog.GetString ("Pushing changes..."), VersionControlOperationType.Push); ThreadPool.QueueUserWorkItem (delegate { try { repo.Push (monitor, remote, branch); @@ -91,13 +92,13 @@ namespace MonoDevelop.VersionControl.Git if (MessageService.RunCustomDialog (dlg) == (int) Gtk.ResponseType.Ok) { dlg.Hide (); if (rebasing) { - using (IProgressMonitor monitor = VersionControlService.GetProgressMonitor (GettextCatalog.GetString ("Rebasing branch '{0}'...", dlg.SelectedBranch))) { + using (ProgressMonitor monitor = VersionControlService.GetProgressMonitor (GettextCatalog.GetString ("Rebasing branch '{0}'...", dlg.SelectedBranch))) { if (dlg.IsRemote) repo.Fetch (monitor); repo.Rebase (dlg.SelectedBranch, dlg.StageChanges ? GitUpdateOptions.SaveLocalChanges : GitUpdateOptions.None, monitor); } } else { - using (IProgressMonitor monitor = VersionControlService.GetProgressMonitor (GettextCatalog.GetString ("Merging branch '{0}'...", dlg.SelectedBranch))) { + using (ProgressMonitor monitor = VersionControlService.GetProgressMonitor (GettextCatalog.GetString ("Merging branch '{0}'...", dlg.SelectedBranch))) { if (dlg.IsRemote) repo.Fetch (monitor); repo.Merge (dlg.SelectedBranch, dlg.StageChanges ? GitUpdateOptions.SaveLocalChanges : GitUpdateOptions.None, monitor); @@ -115,13 +116,13 @@ namespace MonoDevelop.VersionControl.Git MessageService.ShowCustomDialog (dlg); } - public static void SwitchToBranch (GitRepository repo, string branch) + public async static void SwitchToBranch (GitRepository repo, string branch) { MessageDialogProgressMonitor monitor = new MessageDialogProgressMonitor (true, false, false, true); try { IdeApp.Workbench.AutoReloadDocuments = true; IdeApp.Workbench.LockGui (); - ThreadPool.QueueUserWorkItem (delegate { + await Task.Factory.StartNew (delegate { try { repo.SwitchToBranch (monitor, branch); } catch (Exception ex) { @@ -130,18 +131,17 @@ namespace MonoDevelop.VersionControl.Git monitor.Dispose (); } }); - monitor.AsyncOperation.WaitForCompleted (); } finally { IdeApp.Workbench.AutoReloadDocuments = false; IdeApp.Workbench.UnlockGui (); } } - public static IAsyncOperation ApplyStash (Stash s) + public static Task ApplyStash (Stash s) { MessageDialogProgressMonitor monitor = new MessageDialogProgressMonitor (true, false, false, true); var statusTracker = IdeApp.Workspace.GetFileStatusTracker (); - ThreadPool.QueueUserWorkItem (delegate { + var t = Task.Factory.StartNew (delegate { try { MergeCommandResult result; using (var gm = new GitMonitor (monitor)) @@ -156,10 +156,10 @@ namespace MonoDevelop.VersionControl.Git statusTracker.NotifyChanges (); } }); - return monitor.AsyncOperation; + return t; } - public static void ReportStashResult (IProgressMonitor monitor, MergeCommandResult result) + public static void ReportStashResult (ProgressMonitor monitor, MergeCommandResult result) { if (result.GetMergeStatus () == MergeStatus.FAILED) { string msg = GettextCatalog.GetString ("Stash operation failed."); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs index 437c28627f..9ee17b62cb 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs @@ -27,31 +27,32 @@ using System; using MonoDevelop.Ide.Templates; using MonoDevelop.Core; using MonoDevelop.Projects; +using System.Linq; namespace MonoDevelop.VersionControl.Git { sealed class GitSupportFeature: ISolutionItemFeature { - public FeatureSupportLevel GetSupportLevel (SolutionFolder parentFolder, SolutionItem entry) + public FeatureSupportLevel GetSupportLevel (SolutionFolder parentFolder, SolutionFolderItem entry) { if (parentFolder != null && !parentFolder.ParentSolution.FileName.IsNullOrEmpty && System.IO.File.Exists (parentFolder.ParentSolution.FileName)) return FeatureSupportLevel.NotSupported; return FeatureSupportLevel.SupportedByDefault; } - public Gtk.Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionItem entry) + public Gtk.Widget CreateFeatureEditor (SolutionFolder parentCombine, SolutionFolderItem entry) { Gtk.Label label = new Gtk.Label (GettextCatalog.GetString ("A new local Git Repository for the solution will be created")); label.Show (); return label; } - public string Validate (SolutionFolder parentCombine, SolutionItem entry, Gtk.Widget editor) + public string Validate (SolutionFolder parentCombine, SolutionFolderItem entry, Gtk.Widget editor) { return null; } - public void ApplyFeature (SolutionFolder parentFolder, SolutionItem entry, Gtk.Widget editor) + public void ApplyFeature (SolutionFolder parentFolder, SolutionFolderItem entry, Gtk.Widget editor) { // The solution may not be saved yet if (parentFolder.ParentSolution.FileName.IsNullOrEmpty || !System.IO.File.Exists (parentFolder.ParentSolution.FileName)) @@ -67,7 +68,7 @@ namespace MonoDevelop.VersionControl.Git GitUtil.Init (sol.BaseDirectory, null); GitRepository gitRepo = new GitRepository (sol.BaseDirectory, null); - gitRepo.Add (sol.GetItemFiles (true).ToArray (), false, new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor ()); + gitRepo.Add (sol.GetItemFiles (true).ToArray (), false, new MonoDevelop.Core.ProgressMonitor ()); } public string Title { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs index 2b56ef3e51..5ec0df4cbf 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs @@ -38,6 +38,7 @@ using NGit.Transport; using NGit.Diff; using NGit.Internal; using System; +using ProgressMonitor = MonoDevelop.Core.ProgressMonitor; namespace MonoDevelop.VersionControl.Git { @@ -287,7 +288,7 @@ namespace MonoDevelop.VersionControl.Git return repo; } - public static MergeCommandResult MergeTrees (ProgressMonitor monitor, NGit.Repository repo, RevCommit srcBase, RevCommit srcCommit, string sourceDisplayName, bool commitResult) + public static MergeCommandResult MergeTrees (NGit.ProgressMonitor monitor, NGit.Repository repo, RevCommit srcBase, RevCommit srcCommit, string sourceDisplayName, bool commitResult) { RevCommit newHead; RevWalk revWalk = new RevWalk(repo); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs index ccf2f2e338..be5d4fd6d1 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs @@ -300,7 +300,7 @@ namespace MonoDevelop.VersionControl.Git } } - internal MergeCommandResult Apply (ProgressMonitor monitor, Stash stash) + internal MergeCommandResult Apply (NGit.ProgressMonitor monitor, Stash stash) { monitor.Start (1); monitor.BeginTask ("Applying stash", 100); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs index b546e803fc..284522c521 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs @@ -93,13 +93,11 @@ namespace MonoDevelop.VersionControl.Git return (Stash) store.GetValue (it, 0); } - void ApplyStashAndRemove(Stash s) + async void ApplyStashAndRemove (Stash s) { using (IdeApp.Workspace.GetFileStatusTracker ()) { - GitService.ApplyStash (s).Completed += delegate(IAsyncOperation op) { - if (op.Success) - stashes.Remove (s); - }; + await GitService.ApplyStash (s); + stashes.Remove (s); } } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient.cs index fe6ecd5e69..c331c3b3da 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient.cs @@ -146,7 +146,6 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { public abstract IntPtr client_get_wc_root (out IntPtr wcroot_abspath, string local_abspath, IntPtr ctx, IntPtr result_pool, IntPtr scratch_pool); - // TODO: Check if intptr public abstract IntPtr strerror (int statcode, byte[] buf, int bufsize); public abstract IntPtr path_internal_style (string path, IntPtr pool); @@ -617,8 +616,56 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { Locked, Unlocked, FailedLock, - FailedUnlock - // TODO: Add more enum data + FailedUnlock, + Exists, + ChangelistSet, + ChangelistClear, + ChangelistMoved, + MergeBegin, + ForeignMergeBegin, + UpdateReplace, + PropertyAdded, + PropertyDeleted, + PropertyDeletedNonexistent, + RevpropSet, + RevpropDeleted, + MergeCompleted, + TreeConflict, + FailedExternal, + UpdateStarted, + UpdateSkipObstruction, + UpdateSkipWorkingOnly, + UpdateSkipAccessDenied, + UpdateExternalRemoved, + UpdateShadowedAdd, + UpdateShadowedDelete, + MergeRecordInfo, + UpgradedPath, + MergeRecordInfoBegin, + MergeElideInfo, + Patch, + PatchAppliedHunk, + PatchRejectedHunk, + PatchHunkAlreadyApplied, + CommitCopied, + CommitCopiedReplaced, + UrlRedirect, + PathNonexistent, + Exclude, + FailedConflict, + FailedMissing, + FailedOutOfDate, + FailedNoParent, + FailedLocked, + FailedForbiddenByServer, + SkipConflicted, + UpdateBrokenLock, + FailedObstruction, + ConflictResolverStarting, + ConflictResolverDone, + LeftLocalModifications, + ForeignCopyBegin, + MoveBroken, } public enum NotifyState { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs index b94c055d25..a27a322a82 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs @@ -11,6 +11,8 @@ using svn_revnum_t = System.IntPtr; using size_t = System.Int32; using off_t = System.Int64; using MonoDevelop.Projects.Text; +using System.Threading; +using System.Linq; namespace MonoDevelop.VersionControl.Subversion.Unix { @@ -77,6 +79,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return error.message; else { byte[] buf = new byte [300]; + // Caller will handle the lock. Svn.strerror (error.apr_err, buf, buf.Length); return Encoding.UTF8.GetString (buf); } @@ -86,16 +89,25 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { IntPtr p; + // Caller will handle the lock. Apr.pool_create_ex (out p, parent, IntPtr.Zero, IntPtr.Zero); if (p == IntPtr.Zero) throw new InvalidOperationException ("Could not create an APR pool."); return p; } + + internal static void destroypool (IntPtr pool) + { + // Caller will handle lock. + if (pool != IntPtr.Zero) + Apr.pool_destroy (pool); + } public static string NormalizePath (string pathOrUrl, IntPtr localpool) { if (pathOrUrl == null) return null; + // Caller will handle the lock. IntPtr res = Svn.path_internal_style (pathOrUrl, localpool); return Marshal.PtrToStringAnsi (res); } @@ -129,7 +141,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix public static string GetVersion () { - IntPtr ptr = Svn.client_version (); + IntPtr ptr; + lock (Svn) + ptr = Svn.client_version (); LibSvnClient.svn_version_t ver = (LibSvnClient.svn_version_t)Marshal.PtrToStructure (ptr, typeof(LibSvnClient.svn_version_t)); return ver.major + "." + ver.minor + "." + ver.patch; } @@ -173,26 +187,6 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return new UnixSvnBackend (); } - public override string GetPathUrl (FilePath path) - { - if (path == FilePath.Null) - throw new ArgumentNullException(); - - IntPtr ret = IntPtr.Zero; - IntPtr localpool = newpool (IntPtr.Zero); - try { - string npath = NormalizePath (path, localpool); - CheckError (Svn.client_url_from_path (ref ret, npath, localpool)); - } finally { - Apr.pool_destroy (localpool); - } - - if (ret == IntPtr.Zero) - return null; - - return Marshal.PtrToStringAnsi (ret); - } - public override string GetDirectoryDotSvn (FilePath path) { if (Pre_1_7) @@ -240,15 +234,17 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return SvnClient.newpool (parent); } + static void destroypool (IntPtr pool) + { + SvnClient.destroypool (pool); + } + bool disposed; readonly IntPtr auth_baton; readonly IntPtr pool; readonly IntPtr ctx; - readonly object sync = new object(); - bool inProgress; - - IProgressMonitor updatemonitor; + ProgressMonitor updatemonitor; ArrayList updateFileList; string commitmessage; @@ -274,109 +270,113 @@ namespace MonoDevelop.VersionControl.Subversion.Unix public UnixSvnBackend () { - // Allocate the APR pool and the SVN client context. - pool = newpool (IntPtr.Zero); + lock (svn) { + // Allocate the APR pool and the SVN client context. + pool = newpool (IntPtr.Zero); - // Make sure the config directory is properly created. - // If the config directory and specifically the subdirectories - // for the authentication providers don't exist, authentication - // data won't be saved and no error is given. - svn.config_ensure (null, pool); + // Make sure the config directory is properly created. + // If the config directory and specifically the subdirectories + // for the authentication providers don't exist, authentication + // data won't be saved and no error is given. + svn.config_ensure (null, pool); - // Load user and system configuration - svn.config_get_config (ref config_hash, null, pool); + // Load user and system configuration + svn.config_get_config (ref config_hash, null, pool); - if (svn.client_create_context (out ctx, pool) != IntPtr.Zero) - throw new InvalidOperationException ("Could not create a Subversion client context."); + if (svn.client_create_context (out ctx, pool) != IntPtr.Zero) + throw new InvalidOperationException ("Could not create a Subversion client context."); - // Set the callbacks on the client context structure. - notify_func = new LibSvnClient.svn_wc_notify_func2_t (svn_wc_notify_func_t_impl); - Marshal.WriteIntPtr (ctx, - (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "NotifyFunc2"), - Marshal.GetFunctionPointerForDelegate (notify_func)); - log_func = new LibSvnClient.svn_client_get_commit_log_t (svn_client_get_commit_log_impl); - Marshal.WriteIntPtr (ctx, - (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "LogMsgFunc"), - Marshal.GetFunctionPointerForDelegate (log_func)); - progress_func = new LibSvnClient.svn_ra_progress_notify_func_t (svn_ra_progress_notify_func_t_impl); - Marshal.WriteIntPtr (ctx, - (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "progress_func"), - Marshal.GetFunctionPointerForDelegate (progress_func)); - cancel_func = new LibSvnClient.svn_cancel_func_t (svn_cancel_func_t_impl); - Marshal.WriteIntPtr (ctx, - (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "cancel_func"), - Marshal.GetFunctionPointerForDelegate (cancel_func)); - - Marshal.WriteIntPtr (ctx, - (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "config"), - config_hash); - - if (!SvnClient.Pre_1_7) { - IntPtr scratch = newpool (IntPtr.Zero); - svn.wc_context_create (out wc_ctx, IntPtr.Zero, pool, scratch); + // Set the callbacks on the client context structure. + notify_func = new LibSvnClient.svn_wc_notify_func2_t (svn_wc_notify_func_t_impl); Marshal.WriteIntPtr (ctx, - (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "wc_ctx"), - wc_ctx); - apr.pool_destroy (scratch); - } + (int)Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "NotifyFunc2"), + Marshal.GetFunctionPointerForDelegate (notify_func)); + log_func = new LibSvnClient.svn_client_get_commit_log_t (svn_client_get_commit_log_impl); + Marshal.WriteIntPtr (ctx, + (int)Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "LogMsgFunc"), + Marshal.GetFunctionPointerForDelegate (log_func)); + progress_func = new LibSvnClient.svn_ra_progress_notify_func_t (svn_ra_progress_notify_func_t_impl); + Marshal.WriteIntPtr (ctx, + (int)Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "progress_func"), + Marshal.GetFunctionPointerForDelegate (progress_func)); + cancel_func = new LibSvnClient.svn_cancel_func_t (svn_cancel_func_t_impl); + Marshal.WriteIntPtr (ctx, + (int)Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "cancel_func"), + Marshal.GetFunctionPointerForDelegate (cancel_func)); - IntPtr providers = apr.array_make (pool, 16, IntPtr.Size); - IntPtr item; + Marshal.WriteIntPtr (ctx, + (int)Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "config"), + config_hash); + + if (!SvnClient.Pre_1_7) { + IntPtr scratch = newpool (IntPtr.Zero); + svn.wc_context_create (out wc_ctx, IntPtr.Zero, pool, scratch); + Marshal.WriteIntPtr (ctx, + (int)Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "wc_ctx"), + wc_ctx); + apr.pool_destroy (scratch); + } + + IntPtr providers = apr.array_make (pool, 16, IntPtr.Size); + IntPtr item; - // The main disk-caching auth providers, for both - // 'username/password' creds and 'username' creds. + // The main disk-caching auth providers, for both + // 'username/password' creds and 'username' creds. - item = apr.array_push (providers); - svn.client_get_simple_provider (item, pool); + item = apr.array_push (providers); + svn.client_get_simple_provider (item, pool); - item = apr.array_push (providers); - svn.client_get_username_provider (item, pool); + item = apr.array_push (providers); + svn.client_get_username_provider (item, pool); - // The server-cert, client-cert, and client-cert-password providers + // The server-cert, client-cert, and client-cert-password providers - item = apr.array_push (providers); - svn.client_get_ssl_server_trust_file_provider (item, pool); + item = apr.array_push (providers); + svn.client_get_ssl_server_trust_file_provider (item, pool); - item = apr.array_push (providers); - svn.client_get_ssl_client_cert_file_provider (item, pool); + item = apr.array_push (providers); + svn.client_get_ssl_client_cert_file_provider (item, pool); - item = apr.array_push (providers); - svn.client_get_ssl_client_cert_pw_file_provider (item, pool); + item = apr.array_push (providers); + svn.client_get_ssl_client_cert_pw_file_provider (item, pool); - // Two basic prompt providers: username/password, and just username. + // Two basic prompt providers: username/password, and just username. - item = apr.array_push (providers); - svn.client_get_simple_prompt_provider (item, OnAuthSimplePromptCallback, IntPtr.Zero, 2, pool); + item = apr.array_push (providers); + svn.client_get_simple_prompt_provider (item, OnAuthSimplePromptCallback, IntPtr.Zero, 2, pool); - item = apr.array_push (providers); - svn.client_get_username_prompt_provider (item, OnAuthUsernamePromptCallback, IntPtr.Zero, 2, pool); + item = apr.array_push (providers); + svn.client_get_username_prompt_provider (item, OnAuthUsernamePromptCallback, IntPtr.Zero, 2, pool); - // Three ssl prompt providers, for server-certs, client-certs, - // and client-cert-passphrases. + // Three ssl prompt providers, for server-certs, client-certs, + // and client-cert-passphrases. - item = apr.array_push (providers); - svn.client_get_ssl_server_trust_prompt_provider (item, OnAuthSslServerTrustPromptCallback, IntPtr.Zero, pool); + item = apr.array_push (providers); + svn.client_get_ssl_server_trust_prompt_provider (item, OnAuthSslServerTrustPromptCallback, IntPtr.Zero, pool); - item = apr.array_push (providers); - svn.client_get_ssl_client_cert_prompt_provider (item, OnAuthSslClientCertPromptCallback, IntPtr.Zero, 2, pool); + item = apr.array_push (providers); + svn.client_get_ssl_client_cert_prompt_provider (item, OnAuthSslClientCertPromptCallback, IntPtr.Zero, 2, pool); - item = apr.array_push (providers); - svn.client_get_ssl_client_cert_pw_prompt_provider (item, OnAuthSslClientCertPwPromptCallback, IntPtr.Zero, 2, pool); + item = apr.array_push (providers); + svn.client_get_ssl_client_cert_pw_prompt_provider (item, OnAuthSslClientCertPwPromptCallback, IntPtr.Zero, 2, pool); - // Create the authentication baton - svn.auth_open (out auth_baton, providers, pool); + // Create the authentication baton + svn.auth_open (out auth_baton, providers, pool); - Marshal.WriteIntPtr (ctx, - (int) Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "auth_baton"), - auth_baton); + Marshal.WriteIntPtr (ctx, + (int)Marshal.OffsetOf (typeof(LibSvnClient.svn_client_ctx_t), "auth_baton"), + auth_baton); + } } public void Dispose () { - if (!disposed) { - if (apr != null) - apr.pool_destroy(pool); - disposed = true; + lock (svn) { + if (!disposed) { + if (apr != null) + apr.pool_destroy (pool); + disposed = true; + } } } @@ -387,14 +387,15 @@ namespace MonoDevelop.VersionControl.Subversion.Unix static IntPtr GetCancelError () { - LibSvnClient.svn_error_t error = new LibSvnClient.svn_error_t (); - error.apr_err = LibApr.APR_OS_START_USEERR; - error.message = "Operation cancelled."; - // Subversion destroys the error pool to dispose the error object, // so we need to use a non-shared pool. IntPtr localpool = newpool (IntPtr.Zero); - error.pool = localpool; + var error = new LibSvnClient.svn_error_t { + apr_err = LibApr.APR_OS_START_USEERR, + message = "Operation cancelled.", + pool = localpool, + }; + return apr.pcalloc (localpool, error); } @@ -420,8 +421,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix static readonly LibSvnClient.svn_auth_username_prompt_func_t OnAuthUsernamePromptCallback = OnAuthUsernamePrompt; static IntPtr OnAuthUsernamePrompt (ref IntPtr cred, IntPtr baton, string realm, bool may_save, IntPtr pool) { - LibSvnClient.svn_auth_cred_username_t data = new LibSvnClient.svn_auth_cred_username_t (); - data.username = "";
+ LibSvnClient.svn_auth_cred_username_t data = new LibSvnClient.svn_auth_cred_username_t { + username = "", + };
bool ms; if (UserNameAuthenticationPrompt (realm, may_save, ref data.username, out ms)) {
data.may_save = ms; @@ -438,15 +440,16 @@ namespace MonoDevelop.VersionControl.Subversion.Unix static readonly LibSvnClient.svn_auth_ssl_server_trust_prompt_func_t OnAuthSslServerTrustPromptCallback = OnAuthSslServerTrustPrompt; static IntPtr OnAuthSslServerTrustPrompt (ref IntPtr cred, IntPtr baton, string realm, UInt32 failures, ref LibSvnClient.svn_auth_ssl_server_cert_info_t cert_info, bool may_save, IntPtr pool) { - LibSvnClient.svn_auth_cred_ssl_server_trust_t data = new LibSvnClient.svn_auth_cred_ssl_server_trust_t (); - - CertficateInfo ci = new CertficateInfo (); - ci.AsciiCert = cert_info.ascii_cert; - ci.Fingerprint = cert_info.fingerprint; - ci.HostName = cert_info.hostname; - ci.IssuerName = cert_info.issuer_dname; - ci.ValidFrom = cert_info.valid_from; - ci.ValidUntil = cert_info.valid_until; + var data = new LibSvnClient.svn_auth_cred_ssl_server_trust_t (); + + var ci = new CertficateInfo { + AsciiCert = cert_info.ascii_cert, + Fingerprint = cert_info.fingerprint, + HostName = cert_info.hostname, + IssuerName = cert_info.issuer_dname, + ValidFrom = cert_info.valid_from, + ValidUntil = cert_info.valid_until, + }; SslFailure accepted_failures;
bool ms; @@ -466,7 +469,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix static readonly LibSvnClient.svn_auth_ssl_client_cert_prompt_func_t OnAuthSslClientCertPromptCallback = OnAuthSslClientCertPrompt; static IntPtr OnAuthSslClientCertPrompt (ref IntPtr cred, IntPtr baton, string realm, bool may_save, IntPtr pool) { - LibSvnClient.svn_auth_cred_ssl_client_cert_t data = new LibSvnClient.svn_auth_cred_ssl_client_cert_t ();
+ var data = new LibSvnClient.svn_auth_cred_ssl_client_cert_t ();
bool ms; if (SslClientCertAuthenticationPrompt (realm, may_save, out data.cert_file, out ms)) {
data.may_save = ms; @@ -483,7 +486,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix static readonly LibSvnClient.svn_auth_ssl_client_cert_pw_prompt_func_t OnAuthSslClientCertPwPromptCallback = OnAuthSslClientCertPwPrompt; static IntPtr OnAuthSslClientCertPwPrompt (ref IntPtr cred, IntPtr baton, string realm, bool may_save, IntPtr pool) { - LibSvnClient.svn_auth_cred_ssl_client_cert_pw_t data;
+ var data = new LibSvnClient.svn_auth_cred_ssl_client_cert_pw_t ();
bool ms; if (SslClientCertPwAuthenticationPrompt (realm, may_save, out data.password, out ms)) {
data.may_save = ms; @@ -513,6 +516,17 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { return SvnClient.NormalizePath (pathOrUrl, localpool); } + + static IntPtr NormalizePaths (IntPtr pool, params FilePath[] paths) + { + IntPtr array = apr.array_make (pool, 0, IntPtr.Size); + foreach (string path in paths) { + string pathorurl = NormalizePath (path, pool); + IntPtr item = apr.array_push (array); + Marshal.WriteIntPtr (item, apr.pstrdup (pool, pathorurl)); + } + return array; + } public override IEnumerable<DirectoryEntry> ListUrl (string url, bool recurse, SvnRevision rev) { @@ -520,12 +534,13 @@ namespace MonoDevelop.VersionControl.Subversion.Unix throw new ArgumentNullException (); LibSvnClient.Rev revision = (LibSvnClient.Rev) rev; - IntPtr localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; List<DirectoryEntry> items = new List<DirectoryEntry> (); try { IntPtr hash; - + + localpool = TryStartOperation (null); url = NormalizePath (url, localpool); CheckError (svn.client_ls (out hash, url, ref revision, @@ -538,22 +553,22 @@ namespace MonoDevelop.VersionControl.Subversion.Unix apr.hash_this (item, out nameptr, out namelen, out val); string name = Marshal.PtrToStringAnsi (nameptr); - LibSvnClient.svn_dirent_t ent = (LibSvnClient.svn_dirent_t) Marshal.PtrToStructure (val, typeof (LibSvnClient.svn_dirent_t)); + var ent = (LibSvnClient.svn_dirent_t) Marshal.PtrToStructure (val, typeof (LibSvnClient.svn_dirent_t)); item = apr.hash_next (item); - DirectoryEntry dent = new DirectoryEntry (); - dent.Name = name; - dent.IsDirectory = ent.kind == LibSvnClient.svn_node_kind_t.Dir; - dent.Size = ent.size; - dent.HasProps = ent.has_props; - dent.CreatedRevision = (int) ent.created_rev; - dent.Time = new DateTime (1970, 1, 1).AddTicks(ent.time * 10); - dent.LastAuthor = ent.last_author; + var dent = new DirectoryEntry { + Name = name, + IsDirectory = ent.kind == LibSvnClient.svn_node_kind_t.Dir, + Size = ent.size, + HasProps = ent.has_props, + CreatedRevision = (int) ent.created_rev, + Time = new DateTime (1970, 1, 1).AddTicks(ent.time * 10), + LastAuthor = ent.last_author, + }; items.Add (dent); } } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } return items; @@ -568,8 +583,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix ArrayList ret = new ArrayList (); StatusCollector collector = new StatusCollector (ret); - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); string pathorurl = NormalizePath (path, localpool); CheckError (svn.client_status (IntPtr.Zero, pathorurl, ref revision, collector.Func, @@ -584,8 +600,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix if (e.ErrorCode != 155007 && e.ErrorCode != 155008) throw; } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } List<VersionInfo> nodes = new List<VersionInfo>(); @@ -605,8 +620,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix List<SvnRevision> ret = new List<SvnRevision> (); IntPtr strptr = IntPtr.Zero; - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); IntPtr array = apr.array_make (localpool, 0, IntPtr.Size); IntPtr first = apr.array_push (array); string pathorurl = NormalizePath (path, localpool); @@ -621,8 +637,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } finally { if (strptr != IntPtr.Zero) Marshal.FreeHGlobal (strptr); - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } return ret; @@ -649,13 +664,13 @@ namespace MonoDevelop.VersionControl.Subversion.Unix Annotation[] annotations = new Annotation [numAnnotations]; AnnotationCollector collector = new AnnotationCollector (annotations); - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); string path = NormalizePath (file.FullPath, localpool); CheckError (svn.client_blame (path, ref revisionStart, ref revisionEnd, collector.Func, IntPtr.Zero, ctx, localpool)); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } return annotations; @@ -695,8 +710,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix LibSvnClient.Rev revision = (LibSvnClient.Rev) rev; - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); pathorurl = NormalizePath (pathorurl, localpool); StreamCollector collector = new StreamCollector (stream); IntPtr svnstream = svn.stream_create (IntPtr.Zero, localpool); @@ -705,12 +721,11 @@ namespace MonoDevelop.VersionControl.Subversion.Unix // Otherwise, it will use Head as peg and it will throw exceptions. CheckError (svn.client_cat2 (svnstream, pathorurl, ref revision, ref revision, ctx, localpool), 195007); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Update (FilePath path, bool recurse, IProgressMonitor monitor) + public override void Update (FilePath path, bool recurse, ProgressMonitor monitor) { if (path == FilePath.Null || monitor == null) throw new ArgumentNullException(); @@ -718,15 +733,15 @@ namespace MonoDevelop.VersionControl.Subversion.Unix updateFileList = new ArrayList (); LibSvnClient.Rev rev = LibSvnClient.Rev.Head; - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (monitor); string pathorurl = NormalizePath (path, localpool); IntPtr result = Marshal.AllocHGlobal (IntPtr.Size); CheckError (svn.client_update (result, pathorurl, ref rev, recurse, ctx, localpool)); Marshal.FreeHGlobal (result); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); foreach (string file in updateFileList) FileService.NotifyFileChanged (file, true); @@ -735,56 +750,50 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } }
- public override void Revert (FilePath[] paths, bool recurse, IProgressMonitor monitor) + public override void Revert (FilePath[] paths, bool recurse, ProgressMonitor monitor) { if (paths == null || monitor == null) throw new ArgumentNullException(); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { - // Put each item into an APR array. - IntPtr array = apr.array_make (localpool, 0, IntPtr.Size); - foreach (string path in paths) { - string pathorurl = NormalizePath (path, localpool); - IntPtr item = apr.array_push (array); - Marshal.WriteIntPtr (item, apr.pstrdup (localpool, pathorurl)); - } - + localpool = TryStartOperation (monitor); + IntPtr array = NormalizePaths (localpool, paths); CheckError (svn.client_revert (array, recurse, ctx, localpool)); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Add (FilePath path, bool recurse, IProgressMonitor monitor) + public override void Add (FilePath path, bool recurse, ProgressMonitor monitor) { if (path == FilePath.Null || monitor == null) throw new ArgumentNullException (); nb = new notify_baton (); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (monitor); string pathorurl = NormalizePath (path, localpool); CheckError (svn.client_add3 (pathorurl, recurse, true, false, ctx, localpool)); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Checkout (string url, FilePath path, Revision revision, bool recurse, IProgressMonitor monitor) + public override void Checkout (string url, FilePath path, Revision revision, bool recurse, ProgressMonitor monitor) { if (url == null || monitor == null) throw new ArgumentNullException (); if (revision == null) revision = SvnRevision.Head; - LibSvnClient.Rev rev = (LibSvnClient.Rev) revision; + var rev = (LibSvnClient.Rev) revision; nb = new notify_baton (); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (monitor); // Using Uri here because the normalization method doesn't remove the redundant port number when using https url = NormalizePath (new Uri(url).ToString(), localpool); string npath = NormalizePath (path, localpool); @@ -796,27 +805,20 @@ namespace MonoDevelop.VersionControl.Subversion.Unix if (Directory.Exists (path.ParentDirectory)) FileService.DeleteDirectory (path.ParentDirectory); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Commit (FilePath[] paths, string message, IProgressMonitor monitor) + public override void Commit (FilePath[] paths, string message, ProgressMonitor monitor) { if (paths == null || message == null || monitor == null) throw new ArgumentNullException(); nb = new notify_baton (); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { - // Put each item into an APR array. - IntPtr array = apr.array_make (localpool, 0, IntPtr.Size); - foreach (string path in paths) { - string npath = NormalizePath (path, localpool); - IntPtr item = apr.array_push (array); - Marshal.WriteIntPtr (item, apr.pstrdup (localpool, npath)); - } - + localpool = TryStartOperation (monitor); + IntPtr array = NormalizePaths (localpool, paths); IntPtr commit_info = IntPtr.Zero; commitmessage = message; @@ -829,26 +831,20 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } } finally { commitmessage = null; - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Mkdir (string[] paths, string message, IProgressMonitor monitor) + public override void Mkdir (string[] paths, string message, ProgressMonitor monitor) { if (paths == null || monitor == null) throw new ArgumentNullException (); nb = new notify_baton (); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { - // Put each item into an APR array. - IntPtr array = apr.array_make (localpool, paths.Length, IntPtr.Size); - foreach (string path in paths) { - string npath = NormalizePath (path, localpool); - IntPtr item = apr.array_push (array); - Marshal.WriteIntPtr (item, apr.pstrdup (localpool, npath)); - } + localpool = TryStartOperation (monitor); + IntPtr array = NormalizePaths (localpool, paths.Select (p => (FilePath)p).ToArray ()); commitmessage = message; @@ -856,36 +852,29 @@ namespace MonoDevelop.VersionControl.Subversion.Unix CheckError (svn.client_mkdir2 (ref commit_info, array, ctx, localpool)); } finally { commitmessage = null; - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Delete (FilePath path, bool force, IProgressMonitor monitor) + public override void Delete (FilePath path, bool force, ProgressMonitor monitor) { if (path == FilePath.Null || monitor == null) throw new ArgumentNullException (); nb = new notify_baton (); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { - // Put each item into an APR array. - IntPtr array = apr.array_make (localpool, 0, IntPtr.Size); - //foreach (string path in paths) { - string npath = NormalizePath (path, localpool); - IntPtr item = apr.array_push (array); - Marshal.WriteIntPtr (item, apr.pstrdup (localpool, npath)); - //} + localpool = TryStartOperation (monitor); + IntPtr array = NormalizePaths (localpool, path); IntPtr commit_info = IntPtr.Zero; CheckError (svn.client_delete (ref commit_info, array, force, ctx, localpool)); } finally { commitmessage = null; - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Move (FilePath srcPath, FilePath destPath, SvnRevision rev, bool force, IProgressMonitor monitor) + public override void Move (FilePath srcPath, FilePath destPath, SvnRevision rev, bool force, ProgressMonitor monitor) { if (srcPath == FilePath.Null || destPath == FilePath.Null || monitor == null) throw new ArgumentNullException (); @@ -894,29 +883,25 @@ namespace MonoDevelop.VersionControl.Subversion.Unix nb = new notify_baton (); IntPtr commit_info = IntPtr.Zero; - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (monitor); string nsrcPath = NormalizePath (srcPath, localpool); string ndestPath = NormalizePath (destPath, localpool); CheckError (svn.client_move (ref commit_info, nsrcPath, ref revision, ndestPath, force, ctx, localpool)); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } }
- public override void Lock (IProgressMonitor monitor, string comment, bool stealLock, params FilePath[] paths) + public override void Lock (ProgressMonitor monitor, string comment, bool stealLock, params FilePath[] paths) { nb = new notify_baton (); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { - IntPtr array = apr.array_make (localpool, 0, IntPtr.Size); - foreach (string path in paths) { - string npath = NormalizePath (path, localpool); - IntPtr item = apr.array_push (array); - Marshal.WriteIntPtr (item, apr.pstrdup (localpool, npath)); - } + localpool = TryStartOperation (monitor); + IntPtr array = NormalizePaths (localpool, paths); lockFileList = new ArrayList (); requiredLockState = LibSvnClient.NotifyLockState.Locked; @@ -924,23 +909,18 @@ namespace MonoDevelop.VersionControl.Subversion.Unix if (paths.Length != lockFileList.Count) throw new SubversionException ("Lock operation failed."); } finally { - apr.pool_destroy (localpool); lockFileList = null; - TryEndOperation (); + TryEndOperation (localpool); } } - public override void Unlock (IProgressMonitor monitor, bool breakLock, params FilePath[] paths) + public override void Unlock (ProgressMonitor monitor, bool breakLock, params FilePath[] paths) { nb = new notify_baton (); - var localpool = TryStartOperation (monitor); + IntPtr localpool = IntPtr.Zero; try { - IntPtr array = apr.array_make (localpool, 0, IntPtr.Size); - foreach (string path in paths) { - string npath = NormalizePath (path, localpool); - IntPtr item = apr.array_push (array); - Marshal.WriteIntPtr (item, apr.pstrdup (localpool, npath)); - } + localpool = TryStartOperation (monitor); + IntPtr array = NormalizePaths (localpool, paths); lockFileList = new ArrayList (); requiredLockState = LibSvnClient.NotifyLockState.Unlocked; @@ -948,9 +928,8 @@ namespace MonoDevelop.VersionControl.Subversion.Unix if (paths.Length != lockFileList.Count) throw new SubversionException ("Lock operation failed."); } finally { - apr.pool_destroy (localpool); lockFileList = null; - TryEndOperation (); + TryEndOperation (localpool); } }
@@ -964,8 +943,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix LibSvnClient.Rev revision1 = (LibSvnClient.Rev) rev1; LibSvnClient.Rev revision2 = (LibSvnClient.Rev) rev2; - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); IntPtr options = apr.array_make (localpool, 0, IntPtr.Size); fout = Path.GetTempFileName (); @@ -1001,18 +981,17 @@ namespace MonoDevelop.VersionControl.Subversion.Unix FileService.DeleteFile (fout); } catch { } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } } }
- public override void RevertToRevision (FilePath path, Revision revision, IProgressMonitor monitor) + public override void RevertToRevision (FilePath path, Revision revision, ProgressMonitor monitor) { Merge (path, LibSvnClient.Rev.Head, (LibSvnClient.Rev) revision); }
- public override void RevertRevision (FilePath path, Revision revision, IProgressMonitor monitor) + public override void RevertRevision (FilePath path, Revision revision, ProgressMonitor monitor) { SvnRevision srev = (SvnRevision) revision; Merge (path, (LibSvnClient.Rev) srev, LibSvnClient.Rev.Number (srev.Rev - 1)); @@ -1020,8 +999,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix private void Merge (string path, LibSvnClient.Rev revision1, LibSvnClient.Rev revision2) { - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); path = NormalizePath (path, localpool); LibSvnClient.Rev working = LibSvnClient.Rev.Working; CheckError (svn.client_merge_peg2 (path, @@ -1034,117 +1014,110 @@ namespace MonoDevelop.VersionControl.Subversion.Unix ctx, localpool)); } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } } - public override void Ignore (FilePath[] paths) + static void GetProps (StringBuilder props, IntPtr pool, IntPtr result) { - IntPtr hash_item, hash_name, hash_val; + LibSvnClient.svn_string_t new_props; + IntPtr hash_name, hash_val; + IntPtr hash_item = apr.hash_first (pool, result); int length; + + while (hash_item != IntPtr.Zero) { + apr.hash_this (hash_item, out hash_name, out length, out hash_val); + new_props = (LibSvnClient.svn_string_t) Marshal.PtrToStructure (hash_val, typeof (LibSvnClient.svn_string_t)); + props.Append (Marshal.PtrToStringAnsi (new_props.data)); + hash_item = apr.hash_next (hash_item); + } + } + + public override void Ignore (FilePath[] paths) + { IntPtr result; - IntPtr props_ptr = IntPtr.Zero; - StringBuilder props = new StringBuilder (); + IntPtr props_ptr; + var props = new StringBuilder (); string new_path; LibSvnClient.svn_string_t new_props; LibSvnClient.Rev rev = LibSvnClient.Rev.Working; - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); foreach (var path in paths) { new_path = NormalizePath (path, localpool); CheckError (svn.client_propget (out result, "svn:ignore", Path.GetDirectoryName (new_path), ref rev, false, ctx, localpool)); - hash_item = apr.hash_first (localpool, result); - while (hash_item != IntPtr.Zero) { - apr.hash_this (hash_item, out hash_name, out length, out hash_val); - new_props = (LibSvnClient.svn_string_t) Marshal.PtrToStructure (hash_val, typeof (LibSvnClient.svn_string_t)); - props.Append (Marshal.PtrToStringAnsi (new_props.data)); - hash_item = apr.hash_next (hash_item); - } + GetProps (props, localpool, result); + props.AppendLine (Path.GetFileName (new_path)); - new_props = new LibSvnClient.svn_string_t (); - new_props.data = Marshal.StringToHGlobalAnsi (props.ToString ()); - new_props.len = props.Length; + new_props = new LibSvnClient.svn_string_t { + data = Marshal.StringToHGlobalAnsi (props.ToString ()), + len = props.Length, + }; props_ptr = apr.pcalloc (localpool, new_props); CheckError (svn.client_propset ("svn:ignore", props_ptr, Path.GetDirectoryName (new_path), false, localpool)); } } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } } public override void Unignore (FilePath[] paths) { - IntPtr hash_item, hash_name, hash_val; - int length; IntPtr result; - IntPtr props_ptr = IntPtr.Zero; - StringBuilder props = new StringBuilder (); + IntPtr props_ptr; + var props = new StringBuilder (); string new_path; LibSvnClient.svn_string_t new_props; LibSvnClient.Rev rev = LibSvnClient.Rev.Working; int index; string props_str; - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); foreach (var path in paths) { new_path = NormalizePath (path, localpool); CheckError (svn.client_propget (out result, "svn:ignore", Path.GetDirectoryName (new_path), ref rev, false, ctx, localpool)); - hash_item = apr.hash_first (localpool, result); - while (hash_item != IntPtr.Zero) { - apr.hash_this (hash_item, out hash_name, out length, out hash_val); - new_props = (LibSvnClient.svn_string_t) Marshal.PtrToStructure (hash_val, typeof (LibSvnClient.svn_string_t)); - props.Append (Marshal.PtrToStringAnsi (new_props.data)); - hash_item = apr.hash_next (hash_item); - } + GetProps (props, localpool, result); + props_str = props.ToString (); index = props_str.IndexOf (Path.GetFileName (new_path) + Environment.NewLine, StringComparison.Ordinal); props_str = (index < 0) ? props_str : props_str.Remove (index, Path.GetFileName(new_path).Length+1); - new_props = new LibSvnClient.svn_string_t (); - new_props.data = Marshal.StringToHGlobalAnsi (props_str); - new_props.len = props_str.Length; + new_props = new LibSvnClient.svn_string_t { + data = Marshal.StringToHGlobalAnsi (props_str), + len = props_str.Length, + }; props_ptr = apr.pcalloc (localpool, new_props); CheckError (svn.client_propset ("svn:ignore", props_ptr, Path.GetDirectoryName (new_path), false, localpool)); } } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } } public override bool HasNeedLock (FilePath file) { - IntPtr hash_item, hash_name, hash_val; - int length; IntPtr result; - IntPtr props_ptr = IntPtr.Zero; - StringBuilder props = new StringBuilder (); + var props = new StringBuilder (); string new_path; - LibSvnClient.svn_string_t new_props; LibSvnClient.Rev rev = LibSvnClient.Rev.Working; - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); new_path = NormalizePath (file, localpool); CheckError (svn.client_propget (out result, "svn:needs-lock", new_path, ref rev, false, ctx, localpool)); - hash_item = apr.hash_first (localpool, result); - while (hash_item != IntPtr.Zero) { - apr.hash_this (hash_item, out hash_name, out length, out hash_val); - new_props = (LibSvnClient.svn_string_t) Marshal.PtrToStructure (hash_val, typeof (LibSvnClient.svn_string_t)); - props.Append (Marshal.PtrToStringAnsi (new_props.data)); - hash_item = apr.hash_next (hash_item); - } + GetProps (props, localpool, result); + return props.Length != 0; } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } } @@ -1172,32 +1145,19 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return IntPtr.Zero; } - string oldStacktrace = String.Empty; - IntPtr TryStartOperation (IProgressMonitor monitor) + IntPtr TryStartOperation (ProgressMonitor monitor) { - lock (sync) { - if (inProgress) { - var se = new SubversionException ("Another Subversion operation is already in progress."); - se.Data.Add ("OldStacktrace", oldStacktrace); - se.Data.Add ("CurrentStackTrace", Environment.StackTrace); - throw se; - } - oldStacktrace = Environment.StackTrace; - inProgress = true; - updatemonitor = monitor; - progressData = new ProgressData (); - return newpool (pool); - } + Monitor.Enter (svn); + updatemonitor = monitor; + progressData = new ProgressData (); + return newpool (pool); } - void TryEndOperation () + void TryEndOperation (IntPtr pool) { - lock (sync) { - if (!inProgress) - throw new SubversionException ("No Subversion operation is in progress."); - inProgress = false; - updatemonitor = null; - } + destroypool (pool); + updatemonitor = null; + Monitor.Exit (svn); } static VersionInfo CreateNode (LibSvnClient.StatusEnt ent, Repository repo) @@ -1266,15 +1226,16 @@ namespace MonoDevelop.VersionControl.Subversion.Unix IntPtr svn_cancel_func_t_impl (IntPtr baton) { - if (updatemonitor == null || !updatemonitor.IsCancelRequested) + if (updatemonitor == null || !updatemonitor.CancellationToken.IsCancellationRequested) return IntPtr.Zero; - LibSvnClient.svn_error_t err = new LibSvnClient.svn_error_t (); - err.apr_err = 200015; - err.message = "The operation was interrupted"; - IntPtr localpool = newpool (IntPtr.Zero); - err.pool = localpool; + var err = new LibSvnClient.svn_error_t { + apr_err = 200015, + message = "The operation was interrupted", + pool = localpool + }; + return apr.pcalloc (localpool, err); } @@ -1525,9 +1486,11 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return String.Empty; IntPtr result; - IntPtr scratch = newpool (pool); - var localpool = TryStartOperation (null); + IntPtr scratch = IntPtr.Zero; + IntPtr localpool = IntPtr.Zero; try { + localpool = TryStartOperation (null); + scratch = newpool (pool); string new_path = NormalizePath (path.FullPath, localpool); SubversionException e = CheckErrorNoThrow (svn.client_get_wc_root (out result, new_path, ctx, localpool, scratch), null); if (e != null) { @@ -1553,9 +1516,8 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } return Marshal.PtrToStringAnsi (result); } finally { - apr.pool_destroy (localpool); - apr.pool_destroy (scratch); - TryEndOperation (); + destroypool (scratch); + TryEndOperation (localpool); if (TooOld) WorkingCopyFormatPrompt (false, null); @@ -1572,15 +1534,15 @@ namespace MonoDevelop.VersionControl.Subversion.Unix if (!Upgrading || path.IsNullOrEmpty) return; - var localpool = TryStartOperation (null); + IntPtr localpool = IntPtr.Zero; bool tryParent = false; try { + localpool = TryStartOperation (null); CheckError (svn.client_upgrade (path, ctx, localpool)); } catch (Exception e) { tryParent = true; } finally { - apr.pool_destroy (localpool); - TryEndOperation (); + TryEndOperation (localpool); } if (tryParent) @@ -1653,7 +1615,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix apr.hash_this (item, out nameptr, out namelen, out val); string name = Marshal.PtrToStringAnsi (nameptr); - LibSvnClient.svn_log_changed_path_t ch = (LibSvnClient.svn_log_changed_path_t) Marshal.PtrToStructure (val, typeof (LibSvnClient.svn_log_changed_path_t)); + LibSvnClient.svn_log_changed_path_t ch = (LibSvnClient.svn_log_changed_path_t) Marshal.PtrToStructure (val, typeof(LibSvnClient.svn_log_changed_path_t)); item = apr.hash_next (item); RevisionAction ac; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs index 1172cb4bdf..c373e0564a 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs @@ -144,17 +144,17 @@ namespace MonoDevelop.VersionControl.Subversion return true;
}
- protected override void OnLock (IProgressMonitor monitor, params FilePath[] localPaths)
+ protected override void OnLock (ProgressMonitor monitor, params FilePath[] localPaths)
{
Svn.Lock (monitor, "", false, localPaths);
}
- protected override void OnUnlock (IProgressMonitor monitor, params FilePath[] localPaths)
+ protected override void OnUnlock (ProgressMonitor monitor, params FilePath[] localPaths)
{
Svn.Unlock (monitor, false, localPaths);
}
- protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, IProgressMonitor monitor)
+ protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, ProgressMonitor monitor)
{
string url = Url;
if (!serverPath.StartsWith ("/", StringComparison.Ordinal) && !url.EndsWith ("/", StringComparison.Ordinal))
@@ -180,7 +180,7 @@ namespace MonoDevelop.VersionControl.Subversion return new SubversionRepository (VersionControlSystem, paths[0], localPath);
}
- void PublishDir (Set<FilePath> dirs, FilePath dir, bool rec, IProgressMonitor monitor)
+ void PublishDir (Set<FilePath> dirs, FilePath dir, bool rec, ProgressMonitor monitor)
{
if (dirs.Add (dir.CanonicalPath)) {
if (rec) {
@@ -190,31 +190,28 @@ namespace MonoDevelop.VersionControl.Subversion }
}
- protected override void OnUpdate (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
+ protected override void OnUpdate (FilePath[] localPaths, bool recurse, ProgressMonitor monitor)
{
foreach (string path in localPaths)
Svn.Update (path, recurse, monitor);
}
- protected override void OnCommit (ChangeSet changeSet, IProgressMonitor monitor)
+ protected override void OnCommit (ChangeSet changeSet, ProgressMonitor monitor)
{
- List<FilePath> list = new List<FilePath> ();
- foreach (ChangeSetItem it in changeSet.Items)
- list.Add (it.LocalPath);
- Svn.Commit (list.ToArray (), changeSet.GlobalComment, monitor);
+ Svn.Commit (changeSet.Items.Select (it => it.LocalPath).ToArray (), changeSet.GlobalComment, monitor);
}
- void CreateDirectory (string[] paths, string message, IProgressMonitor monitor)
+ void CreateDirectory (string[] paths, string message, ProgressMonitor monitor)
{
Svn.Mkdir (paths, message, monitor);
}
- protected override void OnCheckout (FilePath targetLocalPath, Revision rev, bool recurse, IProgressMonitor monitor)
+ protected override void OnCheckout (FilePath targetLocalPath, Revision rev, bool recurse, ProgressMonitor monitor)
{
Svn.Checkout (this.Url, targetLocalPath, rev, recurse, monitor);
}
- protected override void OnRevert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
+ protected override void OnRevert (FilePath[] localPaths, bool recurse, ProgressMonitor monitor)
{
// If we have an array of paths such as: new [] { "/Foo/Directory", "/Foo/Directory/File1", "/Foo/Directory/File2" }
// svn will successfully revert the first entry (the directory) and then throw an error when trying to revert the
@@ -225,17 +222,17 @@ namespace MonoDevelop.VersionControl.Subversion Svn.Revert (localPaths, recurse, monitor);
}
- protected override void OnRevertRevision (FilePath localPath, Revision revision, IProgressMonitor monitor)
+ protected override void OnRevertRevision (FilePath localPath, Revision revision, ProgressMonitor monitor)
{
Svn.RevertRevision (localPath, revision, monitor);
}
- protected override void OnRevertToRevision (FilePath localPath, Revision revision, IProgressMonitor monitor)
+ protected override void OnRevertToRevision (FilePath localPath, Revision revision, ProgressMonitor monitor)
{
Svn.RevertToRevision (localPath, revision, monitor);
}
- protected override void OnAdd (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
+ protected override void OnAdd (FilePath[] localPaths, bool recurse, ProgressMonitor monitor)
{
foreach (FilePath path in localPaths) {
if (IsVersioned (path) && File.Exists (path) && !Directory.Exists (path)) {
@@ -293,10 +290,10 @@ namespace MonoDevelop.VersionControl.Subversion public string Root {
get {
try {
- UriBuilder ub = new UriBuilder (Url);
- ub.Path = string.Empty;
- ub.Query = string.Empty;
- return ub.ToString ();
+ return new UriBuilder (Url) {
+ Path = string.Empty,
+ Query = string.Empty
+ }.ToString ();
} catch {
return string.Empty;
}
@@ -308,7 +305,7 @@ namespace MonoDevelop.VersionControl.Subversion return (srcRepository is SubversionRepository) && ((SubversionRepository)srcRepository).Root == Root;
}
- protected override void OnMoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor)
+ protected override void OnMoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor)
{
bool destIsVersioned = false;
@@ -343,7 +340,7 @@ namespace MonoDevelop.VersionControl.Subversion }
}
- protected override void OnMoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor)
+ protected override void OnMoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor)
{
if (IsVersioned (localDestPath))
{
@@ -434,7 +431,7 @@ namespace MonoDevelop.VersionControl.Subversion }
}
- void MakeDirVersioned (string dir, IProgressMonitor monitor)
+ void MakeDirVersioned (string dir, ProgressMonitor monitor)
{
if (Directory.Exists (SubversionBackend.GetDirectoryDotSvn (VersionControlSystem, dir)))
return;
@@ -461,7 +458,7 @@ namespace MonoDevelop.VersionControl.Subversion collection.Add(f);
}
- protected override void OnDeleteFiles (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal)
+ protected override void OnDeleteFiles (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal)
{
foreach (string path in localPaths) {
if (IsVersioned (path)) {
@@ -489,7 +486,7 @@ namespace MonoDevelop.VersionControl.Subversion }
}
- protected override void OnDeleteDirectories (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal)
+ protected override void OnDeleteDirectories (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal)
{
foreach (string path in localPaths) {
if (IsVersioned (path)) {
diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs index 0ee35899fe..3ffd857b6f 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs @@ -4,6 +4,7 @@ using System.IO; using MonoDevelop.Core; using MonoDevelop.VersionControl.Subversion.Gui; +using System.Linq; namespace MonoDevelop.VersionControl.Subversion { @@ -23,8 +24,6 @@ namespace MonoDevelop.VersionControl.Subversion } public abstract SubversionBackend CreateBackend (); - - public abstract string GetPathUrl (FilePath path); public override Repository GetRepositoryReference (FilePath path, string id) { @@ -57,17 +56,12 @@ namespace MonoDevelop.VersionControl.Subversion public Revision[] GetHistory (Repository repo, FilePath sourcefile, Revision since) { - List<Revision> revs = new List<Revision>(); - SvnRevision startrev = SvnRevision.Working; SvnRevision sincerev = SvnRevision.First; if (since != null) sincerev = (SvnRevision) since; - - foreach (SvnRevision rev in Log (repo, sourcefile, startrev, sincerev)) - revs.Add (rev); - - return revs.ToArray (); + + return Log (repo, sourcefile, startrev, sincerev).ToArray (); }
public abstract IEnumerable<SvnRevision> Log (Repository repo, FilePath path, SvnRevision revisionStart, SvnRevision revisionEnd); @@ -110,9 +104,8 @@ namespace MonoDevelop.VersionControl.Subversion return VersionInfo.CreateUnversioned (sourcefile, false); if (!sourcefile.IsChildPathOf (srepo.RootPath)) return VersionInfo.CreateUnversioned (sourcefile, false); - - List<VersionInfo> statuses = new List<VersionInfo> (); - statuses.AddRange (Status (repo, sourcefile, SvnRevision.Head, false, false, getRemoteStatus)); + + var statuses = new List<VersionInfo> (Status (repo, sourcefile, SvnRevision.Head, false, false, getRemoteStatus)); if (statuses.Count == 0) return VersionInfo.CreateUnversioned (sourcefile, false); @@ -120,7 +113,7 @@ namespace MonoDevelop.VersionControl.Subversion if (statuses.Count != 1) return VersionInfo.CreateUnversioned (sourcefile, false); - VersionInfo ent = (VersionInfo) statuses[0]; + VersionInfo ent = statuses [0]; if (ent.IsDirectory) return VersionInfo.CreateUnversioned (sourcefile, false); @@ -143,30 +136,28 @@ namespace MonoDevelop.VersionControl.Subversion public VersionInfo[] GetDirectoryVersionInfo (Repository repo, FilePath sourcepath, bool getRemoteStatus, bool recursive) { - List<VersionInfo> list = new List<VersionInfo> (); - list.AddRange (Status (repo, sourcepath, SvnRevision.Head, recursive, true, getRemoteStatus)); - return list.ToArray (); + return Status (repo, sourcepath, SvnRevision.Head, recursive, true, getRemoteStatus).ToArray (); }
public abstract IEnumerable<VersionInfo> Status (Repository repo, FilePath path, SvnRevision revision, bool descendDirs, bool changedItemsOnly, bool remoteStatus);
- public abstract void Update (FilePath path, bool recurse, IProgressMonitor monitor);
+ public abstract void Update (FilePath path, bool recurse, ProgressMonitor monitor);
- public abstract void Commit (FilePath[] paths, string message, IProgressMonitor monitor);
+ public abstract void Commit (FilePath[] paths, string message, ProgressMonitor monitor);
- public abstract void Mkdir (string[] paths, string message, IProgressMonitor monitor);
+ public abstract void Mkdir (string[] paths, string message, ProgressMonitor monitor);
- public abstract void Checkout (string url, FilePath path, Revision rev, bool recurse, IProgressMonitor monitor);
+ public abstract void Checkout (string url, FilePath path, Revision rev, bool recurse, ProgressMonitor monitor);
- public abstract void Revert (FilePath[] paths, bool recurse, IProgressMonitor monitor);
+ public abstract void Revert (FilePath[] paths, bool recurse, ProgressMonitor monitor);
- public abstract void RevertRevision (FilePath path, Revision revision, IProgressMonitor monitor);
+ public abstract void RevertRevision (FilePath path, Revision revision, ProgressMonitor monitor);
- public abstract void RevertToRevision (FilePath path, Revision revision, IProgressMonitor monitor);
+ public abstract void RevertToRevision (FilePath path, Revision revision, ProgressMonitor monitor);
- public abstract void Add (FilePath path, bool recurse, IProgressMonitor monitor); + public abstract void Add (FilePath path, bool recurse, ProgressMonitor monitor); - public abstract void Delete (FilePath path, bool force, IProgressMonitor monitor); + public abstract void Delete (FilePath path, bool force, ProgressMonitor monitor); public abstract void Ignore (FilePath[] paths); @@ -186,16 +177,16 @@ namespace MonoDevelop.VersionControl.Subversion public abstract IEnumerable<DirectoryEntry> ListUrl (string url, bool recurse, SvnRevision rev); - public void Move (FilePath srcPath, FilePath destPath, bool force, IProgressMonitor monitor) + public void Move (FilePath srcPath, FilePath destPath, bool force, ProgressMonitor monitor) { Move (srcPath, destPath, SvnRevision.Head, force, monitor); }
- public abstract void Move (FilePath srcPath, FilePath destPath, SvnRevision rev, bool force, IProgressMonitor monitor);
+ public abstract void Move (FilePath srcPath, FilePath destPath, SvnRevision rev, bool force, ProgressMonitor monitor);
- public abstract void Lock (IProgressMonitor monitor, string comment, bool stealLock, params FilePath[] paths);
+ public abstract void Lock (ProgressMonitor monitor, string comment, bool stealLock, params FilePath[] paths);
- public abstract void Unlock (IProgressMonitor monitor, bool breakLock, params FilePath[] paths);
+ public abstract void Unlock (ProgressMonitor monitor, bool breakLock, params FilePath[] paths);
public string GetUnifiedDiff (FilePath path, bool recursive, bool remoteDiff) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs index b9496598a4..95f58746ed 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs @@ -162,9 +162,10 @@ namespace MonoDevelop.VersionControl.Views scroller.VscrollbarPolicy = PolicyType.Automatic; filelist.RowActivated += OnRowActivated; filelist.DiffLineActivated += OnDiffLineActivated; + filelist.CommitSelectionToggled += OnCommitSelectionToggled; cellToggle = new CellRendererToggle(); - cellToggle.Toggled += new ToggledHandler(OnCommitToggledHandler); + cellToggle.Toggled += new ToggledHandler(OnCommitCellToggled); var crc = new CellRendererImage (); crc.StockId = "vc-comment"; colCommit = new TreeViewColumn (); @@ -409,13 +410,14 @@ namespace MonoDevelop.VersionControl.Views filelist.DoPopupMenu = null; filelist.RowActivated -= OnRowActivated; filelist.DiffLineActivated -= OnDiffLineActivated; + filelist.CommitSelectionToggled -= OnCommitSelectionToggled; filelist.TestExpandRow -= OnTestExpandRow; filelist.Selection.Changed -= OnCursorChanged; filelist.Destroy (); filelist = null; } if (cellToggle != null) { - cellToggle.Toggled -= OnCommitToggledHandler; + cellToggle.Toggled -= OnCommitCellToggled; cellToggle.Destroy (); cellToggle = null; } @@ -455,7 +457,7 @@ namespace MonoDevelop.VersionControl.Views ThreadPool.QueueUserWorkItem (delegate { if (fileList != null) { - var group = fileList.GroupBy (v => v.IsDirectory || v.WorkspaceObject is SolutionItem); + var group = fileList.GroupBy (v => v.IsDirectory || v.WorkspaceObject is SolutionFolderItem); foreach (var item in group) { // Is directory. if (item.Key) { @@ -710,11 +712,8 @@ namespace MonoDevelop.VersionControl.Views OnOpen (null, null); } - void OnCommitToggledHandler(object o, ToggledArgs args) { - TreeIter pos; - if (!filestore.GetIterFromString (out pos, args.Path)) - return; - + void ToggleCommitStatus(TreeIter pos) + { string localpath = (string) filestore.GetValue (pos, ColFullPath); if (changeSet.ContainsFile (localpath)) { @@ -728,6 +727,20 @@ namespace MonoDevelop.VersionControl.Views UpdateSelectionStatus (); } + void OnCommitSelectionToggled (object sender, EventArgs e) + { + filelist.Selection.SelectedForeach((model, path, iter) => ToggleCommitStatus(iter)); + } + + void OnCommitCellToggled(object o, ToggledArgs args) + { + TreeIter pos; + if (!filestore.GetIterFromString (out pos, args.Path)) + return; + + ToggleCommitStatus (pos); + } + VersionInfo GetVersionInfo (string file) { foreach (VersionInfo vi in statuses) @@ -1134,6 +1147,32 @@ namespace MonoDevelop.VersionControl.Views { const Gdk.ModifierType selectionModifiers = Gdk.ModifierType.ShiftMask | Gdk.ModifierType.ControlMask; + protected override bool OnKeyPressEvent (Gdk.EventKey evnt) + { + if (evnt.Key == Gdk.Key.Right || evnt.Key == Gdk.Key.KP_Right) { + Selection.SelectedForeach ((model, path, iter) => ExpandRow (path, true)); + return true; + } + + if (evnt.Key == Gdk.Key.Left || evnt.Key == Gdk.Key.KP_Left) { + Selection.SelectedForeach ((model, path, iter) => CollapseRow (path)); + return true; + } + + if (evnt.Key == Gdk.Key.space && CommitSelectionToggled != null) { + CommitSelectionToggled (this, EventArgs.Empty); + return true; + } + + if (evnt.Key == Gdk.Key.Return || evnt.Key == Gdk.Key.KP_Enter) { + if (DiffLineActivated != null) + DiffLineActivated (this, EventArgs.Empty); + return true; + } + + return base.OnKeyPressEvent (evnt); + } + protected override bool OnButtonPressEvent (Gdk.EventButton evnt) { bool keepPos = false; @@ -1228,5 +1267,6 @@ namespace MonoDevelop.VersionControl.Views public Action<Gdk.EventButton> DoPopupMenu; public event EventHandler DiffLineActivated; + public event EventHandler CommitSelectionToggled; } } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/SubviewAttachmentHandler.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/SubviewAttachmentHandler.cs index 9808922e3d..b95b373dea 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/SubviewAttachmentHandler.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/SubviewAttachmentHandler.cs @@ -48,10 +48,10 @@ namespace MonoDevelop.VersionControl.Views if (document == null || !document.IsFile || document.Window.FindView<IDiffView> () >= 0) return; - IWorkspaceObject project = document.Project; + WorkspaceObject project = document.Project; if (project == null) { // Fix for broken .csproj and .sln files not being seen as having a project. - foreach (var projItem in Ide.IdeApp.Workspace.GetAllSolutionItems<UnknownSolutionItem> ()) { + foreach (var projItem in Ide.IdeApp.Workspace.GetAllItems<UnknownSolutionItem> ()) { if (projItem.FileName == document.FileName) { project = projItem; } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.csproj b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.csproj index 937b7abc9f..f4bf6413df 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.csproj +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.csproj @@ -330,7 +330,6 @@ <Compile Include="MonoDevelop.VersionControl\Repository.cs" /> <Compile Include="MonoDevelop.VersionControl\RevertCommand.cs" /> <Compile Include="MonoDevelop.VersionControl\Revision.cs" /> - <Compile Include="MonoDevelop.VersionControl\Task.cs" /> <Compile Include="MonoDevelop.VersionControl\UnknownRepository.cs" /> <Compile Include="MonoDevelop.VersionControl\UpdateCommand.cs" /> <Compile Include="MonoDevelop.VersionControl\UrlBasedRepository.cs" /> @@ -396,6 +395,7 @@ <Compile Include="MonoDevelop.VersionControl.Dialogs\VersionControlSolutionOptionsPanel.cs" /> <Compile Include="AddinInfo.cs" /> <Compile Include="MonoDevelop.VersionControl\VersionControlException.cs" /> + <Compile Include="MonoDevelop.VersionControl\VersionControlTask.cs" /> </ItemGroup> <ItemGroup> <None Include="Makefile.am" /> diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/AddRemoveMoveCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/AddRemoveMoveCommand.cs index 70766591ea..60850e1c15 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/AddRemoveMoveCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/AddRemoveMoveCommand.cs @@ -17,7 +17,7 @@ namespace MonoDevelop.VersionControl return true; } - private class AddWorker : Task { + private class AddWorker : VersionControlTask { VersionControlItemList items; public AddWorker (VersionControlItemList items) @@ -32,7 +32,7 @@ namespace MonoDevelop.VersionControl protected override void Run () { - IProgressMonitor monitor = Monitor; + ProgressMonitor monitor = Monitor; foreach (VersionControlItemList list in items.SplitByRepository ()) list[0].Repository.Add (list.Paths, true, monitor); @@ -108,7 +108,7 @@ namespace MonoDevelop.VersionControl return true; } - private class RemoveWorker : Task { + private class RemoveWorker : VersionControlTask { VersionControlItemList items; public RemoveWorker (VersionControlItemList items) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CheckoutCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CheckoutCommand.cs index 7ecd9340ed..7e03982d5a 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CheckoutCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CheckoutCommand.cs @@ -28,7 +28,7 @@ namespace MonoDevelop.VersionControl } } - class CheckoutWorker : Task + class CheckoutWorker : VersionControlTask { Repository vc; string path; @@ -45,7 +45,7 @@ namespace MonoDevelop.VersionControl return GettextCatalog.GetString ("Checking out {0}...", path); } - protected override IProgressMonitor CreateProgressMonitor () + protected override ProgressMonitor CreateProgressMonitor () { return new MonoDevelop.Core.ProgressMonitoring.AggregatedProgressMonitor ( base.CreateProgressMonitor (), @@ -73,7 +73,7 @@ namespace MonoDevelop.VersionControl return; } - if (Monitor.IsCancelRequested) { + if (Monitor.CancellationToken.IsCancellationRequested) { Monitor.ReportSuccess (GettextCatalog.GetString ("Checkout operation cancelled")); return; } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Commands.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Commands.cs index 6c8d5abea3..5462cd8978 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Commands.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Commands.cs @@ -37,7 +37,7 @@ namespace MonoDevelop.VersionControl VersionControlItemList list = new VersionControlItemList (); WorkspaceItem wob; - SolutionItem sol; + SolutionFolderItem sol; Repository repo = null; wob = IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem; if (wob != null) diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CommitCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CommitCommand.cs index f5257c5979..c3e6e4979c 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CommitCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/CommitCommand.cs @@ -32,7 +32,7 @@ namespace MonoDevelop.VersionControl } } - private class CommitWorker : Task + private class CommitWorker : VersionControlTask { Repository vc; ChangeSet changeSet; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/IgnoreCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/IgnoreCommand.cs index d9f74988ca..48297e4b43 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/IgnoreCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/IgnoreCommand.cs @@ -62,7 +62,7 @@ namespace MonoDevelop.VersionControl }
}
- private class IgnoreWorker : Task
+ private class IgnoreWorker : VersionControlTask
{
VersionControlItemList items;
@@ -125,7 +125,7 @@ namespace MonoDevelop.VersionControl }
}
- private class UnignoreWorker : Task
+ private class UnignoreWorker : VersionControlTask
{
VersionControlItemList items;
diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/LockCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/LockCommand.cs index 66507132e4..46cb65a80c 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/LockCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/LockCommand.cs @@ -43,7 +43,7 @@ namespace MonoDevelop.VersionControl return true; } - private class LockWorker : Task + private class LockWorker : VersionControlTask { VersionControlItemList items; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/PublishCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/PublishCommand.cs index b636e7e3db..5dee5c58c9 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/PublishCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/PublishCommand.cs @@ -10,7 +10,7 @@ namespace MonoDevelop.VersionControl { internal class PublishCommand {
- public static bool Publish (IWorkspaceObject entry, FilePath localPath, bool test) + public static bool Publish (WorkspaceObject entry, FilePath localPath, bool test) { if (test) return VersionControlService.CheckVersionControlInstalled () && VersionControlService.GetRepository (entry) == null; @@ -52,7 +52,7 @@ namespace MonoDevelop.VersionControl return true; }
- static void GetFiles (List<FilePath> files, IWorkspaceObject entry) + static void GetFiles (List<FilePath> files, WorkspaceObject entry) { // Ensure that we strip out all linked files from outside of the solution/projects path. if (entry is IWorkspaceFileObject) @@ -69,7 +69,7 @@ namespace MonoDevelop.VersionControl } } - internal class PublishWorker : Task { + internal class PublishWorker : VersionControlTask { Repository vc;
FilePath path; string moduleName;
diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Repository.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Repository.cs index aef5e0dd2d..aca8706d1d 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Repository.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Repository.cs @@ -372,6 +372,25 @@ namespace MonoDevelop.VersionControl } catch (Exception ex) { LoggingService.LogError ("Version control status query failed", ex); + //Release all items in current batch + foreach (var item in recursiveDirectoryQueryQueueClone) + item.ResetEvent.Set (); + + lock (queryLock) { + queryRunning = false; + + fileQueryQueue.Clear (); + filesInQueryQueue.Clear (); + + directoriesInQueryQueue.Clear (); + directoryQueryQueue.Clear (); + + recursiveDirectoryQueryQueueClone = recursiveDirectoryQueryQueue.ToArray (); + recursiveDirectoriesInQueryQueue.Clear (); + recursiveDirectoryQueryQueue.Clear (); + } + + //Release newly pending foreach (var item in recursiveDirectoryQueryQueueClone) item.ResetEvent.Set (); } @@ -421,29 +440,29 @@ namespace MonoDevelop.VersionControl // Imports a directory into the repository. 'serverPath' is the relative path in the repository. // 'localPath' is the local directory to publish. 'files' is the list of files to add to the new // repository directory (must use absolute local paths). - public Repository Publish (string serverPath, FilePath localPath, FilePath[] files, string message, IProgressMonitor monitor) + public Repository Publish (string serverPath, FilePath localPath, FilePath[] files, string message, ProgressMonitor monitor) { var res = OnPublish (serverPath, localPath, files, message, monitor); ClearCachedVersionInfo (localPath); return res; } - protected abstract Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, IProgressMonitor monitor); + protected abstract Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, ProgressMonitor monitor); // Updates a local file or directory from the repository // Returns a list of updated files - public void Update (FilePath localPath, bool recurse, IProgressMonitor monitor) + public void Update (FilePath localPath, bool recurse, ProgressMonitor monitor) { Update (new FilePath[] { localPath }, recurse, monitor); } - public void Update (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) + public void Update (FilePath[] localPaths, bool recurse, ProgressMonitor monitor) { OnUpdate (localPaths, recurse, monitor); ClearCachedVersionInfo (localPaths); } - protected abstract void OnUpdate (FilePath[] localPaths, bool recurse, IProgressMonitor monitor); + protected abstract void OnUpdate (FilePath[] localPaths, bool recurse, ProgressMonitor monitor); // Called to create a ChangeSet to be used for a commit operation public virtual ChangeSet CreateChangeSet (FilePath basePath) @@ -468,70 +487,70 @@ namespace MonoDevelop.VersionControl } // Commits changes in a set of files or directories into the repository - public void Commit (ChangeSet changeSet, IProgressMonitor monitor) + public void Commit (ChangeSet changeSet, ProgressMonitor monitor) { ClearCachedVersionInfo (changeSet.BaseLocalPath); OnCommit (changeSet, monitor); } - protected abstract void OnCommit (ChangeSet changeSet, IProgressMonitor monitor); + protected abstract void OnCommit (ChangeSet changeSet, ProgressMonitor monitor); // Gets the contents of this repositories into the specified local path - public void Checkout (FilePath targetLocalPath, bool recurse, IProgressMonitor monitor) + public void Checkout (FilePath targetLocalPath, bool recurse, ProgressMonitor monitor) { Checkout (targetLocalPath, null, recurse, monitor); } - public void Checkout (FilePath targetLocalPath, Revision rev, bool recurse, IProgressMonitor monitor) + public void Checkout (FilePath targetLocalPath, Revision rev, bool recurse, ProgressMonitor monitor) { ClearCachedVersionInfo (targetLocalPath); OnCheckout (targetLocalPath, rev, recurse, monitor); } - protected abstract void OnCheckout (FilePath targetLocalPath, Revision rev, bool recurse, IProgressMonitor monitor); + protected abstract void OnCheckout (FilePath targetLocalPath, Revision rev, bool recurse, ProgressMonitor monitor); - public void Revert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) + public void Revert (FilePath[] localPaths, bool recurse, ProgressMonitor monitor) { ClearCachedVersionInfo (localPaths); OnRevert (localPaths, recurse, monitor); } - public void Revert (FilePath localPath, bool recurse, IProgressMonitor monitor) + public void Revert (FilePath localPath, bool recurse, ProgressMonitor monitor) { Revert (new FilePath[] { localPath }, recurse, monitor); } - protected abstract void OnRevert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor); + protected abstract void OnRevert (FilePath[] localPaths, bool recurse, ProgressMonitor monitor); - public void RevertRevision (FilePath localPath, Revision revision, IProgressMonitor monitor) + public void RevertRevision (FilePath localPath, Revision revision, ProgressMonitor monitor) { ClearCachedVersionInfo (localPath); OnRevertRevision (localPath, revision, monitor); } - protected abstract void OnRevertRevision (FilePath localPath, Revision revision, IProgressMonitor monitor); + protected abstract void OnRevertRevision (FilePath localPath, Revision revision, ProgressMonitor monitor); - public void RevertToRevision (FilePath localPath, Revision revision, IProgressMonitor monitor) + public void RevertToRevision (FilePath localPath, Revision revision, ProgressMonitor monitor) { ClearCachedVersionInfo (localPath); OnRevertToRevision (localPath, revision, monitor); } - protected abstract void OnRevertToRevision (FilePath localPath, Revision revision, IProgressMonitor monitor); + protected abstract void OnRevertToRevision (FilePath localPath, Revision revision, ProgressMonitor monitor); // Adds a file or directory to the repository - public void Add (FilePath localPath, bool recurse, IProgressMonitor monitor) + public void Add (FilePath localPath, bool recurse, ProgressMonitor monitor) { Add (new FilePath[] { localPath }, recurse, monitor); } - public void Add (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) + public void Add (FilePath[] localPaths, bool recurse, ProgressMonitor monitor) { OnAdd (localPaths, recurse, monitor); ClearCachedVersionInfo (localPaths); } - protected abstract void OnAdd (FilePath[] localPaths, bool recurse, IProgressMonitor monitor); + protected abstract void OnAdd (FilePath[] localPaths, bool recurse, ProgressMonitor monitor); // Returns true if the file can be moved from source location (and repository) to this repository public virtual bool CanMoveFilesFrom (Repository srcRepository, FilePath localSrcPath, FilePath localDestPath) @@ -545,57 +564,57 @@ namespace MonoDevelop.VersionControl // For example, when moving a file to an unversioned directory, the implementation // might just throw an exception, or it could version the directory, or it could // ask the user what to do. - public void MoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) + public void MoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor) { ClearCachedVersionInfo (localSrcPath, localDestPath); OnMoveFile (localSrcPath, localDestPath, force, monitor); } - protected virtual void OnMoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) + protected virtual void OnMoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor) { File.Move (localSrcPath, localDestPath); } // Moves a directory. This method may be called for versioned and unversioned // files. The default implementetions performs a system file move. - public void MoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) + public void MoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor) { ClearCachedVersionInfo (localSrcPath, localDestPath); OnMoveDirectory (localSrcPath, localDestPath, force, monitor); } - protected virtual void OnMoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) + protected virtual void OnMoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, ProgressMonitor monitor) { - Directory.Move (localSrcPath, localDestPath); + FileService.SystemDirectoryRename (localSrcPath, localDestPath); } // Deletes a file or directory. This method may be called for versioned and unversioned // files. The default implementetions performs a system file delete. - public void DeleteFile (FilePath localPath, bool force, IProgressMonitor monitor, bool keepLocal = true) + public void DeleteFile (FilePath localPath, bool force, ProgressMonitor monitor, bool keepLocal = true) { DeleteFiles (new FilePath[] { localPath }, force, monitor, keepLocal); } - public void DeleteFiles (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal = true) + public void DeleteFiles (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal = true) { OnDeleteFiles (localPaths, force, monitor, keepLocal); ClearCachedVersionInfo (localPaths); } - protected abstract void OnDeleteFiles (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal); + protected abstract void OnDeleteFiles (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal); - public void DeleteDirectory (FilePath localPath, bool force, IProgressMonitor monitor, bool keepLocal = true) + public void DeleteDirectory (FilePath localPath, bool force, ProgressMonitor monitor, bool keepLocal = true) { DeleteDirectories (new FilePath[] { localPath }, force, monitor, keepLocal); } - public void DeleteDirectories (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal = true) + public void DeleteDirectories (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal = true) { OnDeleteDirectories (localPaths, force, monitor, keepLocal); ClearCachedVersionInfo (localPaths); } - protected abstract void OnDeleteDirectories (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal); + protected abstract void OnDeleteDirectories (FilePath[] localPaths, bool force, ProgressMonitor monitor, bool keepLocal); // Called to request write permission for a file. The file may not yet exist. // After the file is modified or created, NotifyFileChanged is called. @@ -620,26 +639,26 @@ namespace MonoDevelop.VersionControl } // Locks a file in the repository so no other users can change it - public void Lock (IProgressMonitor monitor, params FilePath[] localPaths) + public void Lock (ProgressMonitor monitor, params FilePath[] localPaths) { ClearCachedVersionInfo (localPaths); OnLock (monitor, localPaths); } // Locks a file in the repository so no other users can change it - protected virtual void OnLock (IProgressMonitor monitor, params FilePath[] localPaths) + protected virtual void OnLock (ProgressMonitor monitor, params FilePath[] localPaths) { throw new System.NotSupportedException (); } // Unlocks a file in the repository so other users can change it - public void Unlock (IProgressMonitor monitor, params FilePath[] localPaths) + public void Unlock (ProgressMonitor monitor, params FilePath[] localPaths) { ClearCachedVersionInfo (localPaths); OnUnlock (monitor, localPaths); } - protected virtual void OnUnlock (IProgressMonitor monitor, params FilePath[] localPaths) + protected virtual void OnUnlock (ProgressMonitor monitor, params FilePath[] localPaths) { throw new System.NotSupportedException (); } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertCommand.cs index b69500f639..f49c902b47 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertCommand.cs @@ -43,7 +43,7 @@ namespace MonoDevelop.VersionControl } } - private class RevertWorker : Task { + private class RevertWorker : VersionControlTask { VersionControlItemList items; public RevertWorker (VersionControlItemList items) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertRevisionsCommands.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertRevisionsCommands.cs index e0be0ad697..bf4fa3cf85 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertRevisionsCommands.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/RevertRevisionsCommands.cs @@ -75,7 +75,7 @@ namespace MonoDevelop.VersionControl } } - private class RevertWorker : Task { + private class RevertWorker : VersionControlTask { Repository vc; string path; Revision revision; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnknownRepository.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnknownRepository.cs index 030583d3ce..7735cab3f2 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnknownRepository.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnknownRepository.cs @@ -45,52 +45,52 @@ namespace MonoDevelop.VersionControl }
- protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] FilePath, string message, IProgressMonitor monitor) + protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] FilePath, string message, ProgressMonitor monitor) { return null; }
- protected override void OnUpdate (FilePath[] paths, bool recurse, IProgressMonitor monitor) + protected override void OnUpdate (FilePath[] paths, bool recurse, ProgressMonitor monitor) { } - protected override void OnCommit (ChangeSet changeSet, IProgressMonitor monitor) + protected override void OnCommit (ChangeSet changeSet, ProgressMonitor monitor) { }
- protected override void OnCheckout (FilePath path, Revision rev, bool recurse, IProgressMonitor monitor) + protected override void OnCheckout (FilePath path, Revision rev, bool recurse, ProgressMonitor monitor) { }
- protected override void OnRevert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) + protected override void OnRevert (FilePath[] localPaths, bool recurse, ProgressMonitor monitor) { }
- protected override void OnRevertRevision (FilePath localPath, Revision revision, IProgressMonitor monitor) + protected override void OnRevertRevision (FilePath localPath, Revision revision, ProgressMonitor monitor) { }
- protected override void OnRevertToRevision (FilePath localPath, Revision revision, IProgressMonitor monitor) + protected override void OnRevertToRevision (FilePath localPath, Revision revision, ProgressMonitor monitor) { }
- protected override void OnAdd (FilePath[] paths, bool recurse, IProgressMonitor monitor) + protected override void OnAdd (FilePath[] paths, bool recurse, ProgressMonitor monitor) { }
- protected override void OnMoveFile (FilePath srcPath, FilePath destPath, bool force, IProgressMonitor monitor) + protected override void OnMoveFile (FilePath srcPath, FilePath destPath, bool force, ProgressMonitor monitor) { }
- protected override void OnMoveDirectory (FilePath srcPath, FilePath destPath, bool force, IProgressMonitor monitor) + protected override void OnMoveDirectory (FilePath srcPath, FilePath destPath, bool force, ProgressMonitor monitor) { } - protected override void OnDeleteFiles (FilePath[] path, bool force, IProgressMonitor monitor, bool keepLocal) + protected override void OnDeleteFiles (FilePath[] path, bool force, ProgressMonitor monitor, bool keepLocal) { }
- protected override void OnDeleteDirectories (FilePath[] path, bool force, IProgressMonitor monitor, bool keepLocal) + protected override void OnDeleteDirectories (FilePath[] path, bool force, ProgressMonitor monitor, bool keepLocal) { } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnlockCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnlockCommand.cs index 599e3d56f0..90b5cf4f79 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnlockCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UnlockCommand.cs @@ -45,7 +45,7 @@ namespace MonoDevelop.VersionControl return true; } - private class UnlockWorker : Task + private class UnlockWorker : VersionControlTask { VersionControlItemList items; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UpdateCommand.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UpdateCommand.cs index 6677562bb1..838884e603 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UpdateCommand.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/UpdateCommand.cs @@ -16,7 +16,7 @@ namespace MonoDevelop.VersionControl return true; } - private class UpdateWorker : Task { + private class UpdateWorker : VersionControlTask { VersionControlItemList items; public UpdateWorker (VersionControlItemList items) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlCommandHandler.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlCommandHandler.cs index ba12420ea5..009cfe0c50 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlCommandHandler.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlCommandHandler.cs @@ -70,7 +70,7 @@ namespace MonoDevelop.VersionControl { string path; bool isDir; - IWorkspaceObject pentry; + WorkspaceObject pentry; Repository repo; VersionInfo versionInfo = null; @@ -105,8 +105,8 @@ namespace MonoDevelop.VersionControl path = item.FileName; isDir = false; pentry = item; - } else if (obj is IWorkspaceObject) { - pentry = ((IWorkspaceObject)obj); + } else if (obj is WorkspaceObject) { + pentry = ((WorkspaceObject)obj); path = pentry.BaseDirectory; isDir = true; } else diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlFileSystemExtension.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlFileSystemExtension.cs index 4f50281ce9..c77a27fdfc 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlFileSystemExtension.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlFileSystemExtension.cs @@ -52,7 +52,7 @@ namespace MonoDevelop.VersionControl public override void MoveFile (FilePath source, FilePath dest) { - IProgressMonitor monitor = new NullProgressMonitor (); + ProgressMonitor monitor = new ProgressMonitor (); Repository srcRepo = GetRepository (source); Repository dstRepo = GetRepository (dest); @@ -78,7 +78,7 @@ namespace MonoDevelop.VersionControl public override void DeleteFile (FilePath file) { Repository repo = GetRepository (file); - repo.DeleteFile (file, true, new NullProgressMonitor (), false); + repo.DeleteFile (file, true, new ProgressMonitor (), false); } public override void CreateDirectory (FilePath path) @@ -86,12 +86,12 @@ namespace MonoDevelop.VersionControl Repository repo = GetRepository (path); repo.ClearCachedVersionInfo (path); System.IO.Directory.CreateDirectory (path); - repo.Add (path, false, new NullProgressMonitor ()); + repo.Add (path, false, new ProgressMonitor ()); } public override void MoveDirectory (FilePath sourcePath, FilePath destPath) { - IProgressMonitor monitor = new NullProgressMonitor (); + ProgressMonitor monitor = new ProgressMonitor (); Repository srcRepo = GetRepository (sourcePath); Repository dstRepo = GetRepository (destPath); @@ -107,7 +107,7 @@ namespace MonoDevelop.VersionControl public override void DeleteDirectory (FilePath path) { Repository repo = GetRepository (path); - repo.DeleteDirectory (path, true, new NullProgressMonitor (), false); + repo.DeleteDirectory (path, true, new ProgressMonitor (), false); } public override void RequestFileEdit (IEnumerable<FilePath> files) diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlItem.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlItem.cs index c8f3011f0d..7aa84c36ea 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlItem.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlItem.cs @@ -35,11 +35,11 @@ namespace MonoDevelop.VersionControl {
FilePath path;
bool isDirectory;
- IWorkspaceObject workspaceObject;
+ WorkspaceObject workspaceObject;
Repository repository; VersionInfo versionInfo;
- public VersionControlItem (Repository repository, IWorkspaceObject workspaceObject, FilePath path, bool isDirectory, VersionInfo versionInfo)
+ public VersionControlItem (Repository repository, WorkspaceObject workspaceObject, FilePath path, bool isDirectory, VersionInfo versionInfo)
{
this.path = path;
this.repository = repository;
@@ -48,7 +48,7 @@ namespace MonoDevelop.VersionControl this.versionInfo = versionInfo;
}
- public IWorkspaceObject WorkspaceObject { + public WorkspaceObject WorkspaceObject { get { return workspaceObject; } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlNodeExtension.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlNodeExtension.cs index 848be5eba1..a2f9544638 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlNodeExtension.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlNodeExtension.cs @@ -24,7 +24,7 @@ namespace MonoDevelop.VersionControl return typeof(ProjectFile).IsAssignableFrom (dataType) || typeof(SystemFile).IsAssignableFrom (dataType) || typeof(ProjectFolder).IsAssignableFrom (dataType) - || typeof(IWorkspaceObject).IsAssignableFrom (dataType); + || typeof(WorkspaceObject).IsAssignableFrom (dataType); } protected override void Initialize ()
@@ -46,8 +46,8 @@ namespace MonoDevelop.VersionControl // Add status overlays - if (dataObject is IWorkspaceObject) { - IWorkspaceObject ce = (IWorkspaceObject) dataObject; + if (dataObject is WorkspaceObject) { + WorkspaceObject ce = (WorkspaceObject) dataObject; Repository rep = VersionControlService.GetRepository (ce); if (rep != null) {
rep.GetDirectoryVersionInfo (ce.BaseDirectory, false, false); @@ -66,7 +66,7 @@ namespace MonoDevelop.VersionControl return; } - IWorkspaceObject prj; + WorkspaceObject prj; FilePath file; if (dataObject is ProjectFile) { @@ -202,8 +202,8 @@ namespace MonoDevelop.VersionControl return ((ProjectFile) dataObject).FilePath; } else if (dataObject is SystemFile) { return ((SystemFile) dataObject).Path; - } else if (dataObject is IWorkspaceObject) { - return ((IWorkspaceObject)dataObject).BaseDirectory; + } else if (dataObject is WorkspaceObject) { + return ((WorkspaceObject)dataObject).BaseDirectory; } else if (dataObject is ProjectFolder) { return ((ProjectFolder)dataObject).Path; } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlService.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlService.cs index 9d204b4309..f994eb7cfd 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlService.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlService.cs @@ -185,7 +185,7 @@ namespace MonoDevelop.VersionControl } internal static Dictionary<Repository, InternalRepositoryReference> referenceCache = new Dictionary<Repository, InternalRepositoryReference> (); - public static Repository GetRepository (IWorkspaceObject entry) + public static Repository GetRepository (WorkspaceObject entry) { if (IsGloballyDisabled) return null; @@ -437,6 +437,12 @@ namespace MonoDevelop.VersionControl FileStatusChanged (null, args); } } + + static bool ShouldAddFile (ProjectFileEventInfo info) + { + const ProjectItemFlags ignoreFlags = ProjectItemFlags.DontPersist | ProjectItemFlags.Hidden; + return (info.ProjectFile.Flags & ignoreFlags) != ignoreFlags; + } //static void OnFileChanged (object s, ProjectFileEventArgs args) //{ @@ -448,13 +454,14 @@ namespace MonoDevelop.VersionControl static void OnFileAdded (object s, ProjectFileEventArgs e) { FileUpdateEventArgs vargs = new FileUpdateEventArgs (); - IProgressMonitor monitor = null; + ProgressMonitor monitor = null; try { foreach (var repoFiles in e.GroupBy (i => i.Project)) { Repository repo = GetRepository (repoFiles.Key); if (repo == null) continue; - var versionInfos = repo.GetVersionInfo (repoFiles.Select (f => f.ProjectFile.FilePath), VersionInfoQueryFlags.IgnoreCache); + var filePaths = repoFiles.Where (ShouldAddFile).Select (f => f.ProjectFile.FilePath); + var versionInfos = repo.GetVersionInfo (filePaths, VersionInfoQueryFlags.IgnoreCache); FilePath[] paths = versionInfos.Where (i => i.CanAdd).Select (i => i.LocalPath).ToArray (); if (paths.Length > 0) { if (monitor == null) @@ -494,10 +501,10 @@ namespace MonoDevelop.VersionControl } } */ - static void SolutionItemAddFiles (string rootPath, SolutionItem entry, HashSet<string> files) + static void SolutionItemAddFiles (string rootPath, SolutionFolderItem entry, HashSet<string> files) { - if (entry is SolutionEntityItem) { - foreach (var file in ((SolutionEntityItem)entry).GetItemFiles (false)) + if (entry is SolutionItem) { + foreach (var file in ((SolutionItem)entry).GetItemFiles (false)) SolutionItemAddFile (rootPath, files, file); } @@ -507,7 +514,7 @@ namespace MonoDevelop.VersionControl SolutionItemAddFile (rootPath, files, file.FilePath); } } else if (entry is SolutionFolder) { - foreach (SolutionItem ent in ((SolutionFolder) entry).Items) + foreach (SolutionFolderItem ent in ((SolutionFolder) entry).Items) SolutionItemAddFiles (rootPath, ent, files); } } @@ -531,7 +538,7 @@ namespace MonoDevelop.VersionControl return; // handles addition of solutions and projects - SolutionItem parent = (SolutionItem) args.SolutionItem.ParentFolder; + SolutionFolderItem parent = (SolutionFolderItem) args.SolutionItem.ParentFolder; if (parent == null) return; @@ -541,7 +548,7 @@ namespace MonoDevelop.VersionControl if (repo == null) return; - SolutionItem entry = args.SolutionItem; + SolutionFolderItem entry = args.SolutionItem; Repository currentRepo = GetRepository (entry); if (currentRepo != null && currentRepo.VersionControlSystem != repo.VersionControlSystem) { // If the item is already under version control using a different version control system @@ -558,7 +565,7 @@ namespace MonoDevelop.VersionControl var files = new HashSet<string> { path }; SolutionItemAddFiles (path, entry, files); - using (IProgressMonitor monitor = GetStatusMonitor ()) { + using (ProgressMonitor monitor = GetStatusMonitor ()) { var status = repo.GetDirectoryVersionInfo (path, false, true);
foreach (var v in status) {
if (!v.IsVersioned && files.Contains (v.LocalPath))
@@ -572,12 +579,12 @@ namespace MonoDevelop.VersionControl NotifyFileStatusChanged (new FileUpdateEventArgs (repo, parent.BaseDirectory, true)); } - public static IProgressMonitor GetProgressMonitor (string operation) + public static ProgressMonitor GetProgressMonitor (string operation) { return GetProgressMonitor (operation, VersionControlOperationType.Other); } - public static IProgressMonitor GetProgressMonitor (string operation, VersionControlOperationType op) + public static ProgressMonitor GetProgressMonitor (string operation, VersionControlOperationType op) { IconId icon; switch (op) { @@ -586,7 +593,7 @@ namespace MonoDevelop.VersionControl default: icon = "md-version-control"; break; } - IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor ("MonoDevelop.VersionControlOutput", "Version Control", "md-version-control", false, true); + ProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor ("MonoDevelop.VersionControlOutput", "Version Control", "md-version-control", false, true); Pad outPad = IdeApp.Workbench.ProgressMonitors.GetPadForMonitor (monitor); AggregatedProgressMonitor mon = new AggregatedProgressMonitor (monitor); @@ -594,7 +601,7 @@ namespace MonoDevelop.VersionControl return mon; } - static IProgressMonitor GetStatusMonitor () + static ProgressMonitor GetStatusMonitor () { return IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor (GettextCatalog.GetString ("Updating version control repository"), "vc-remote-status", true); } @@ -736,7 +743,7 @@ namespace MonoDevelop.VersionControl } } - public static CommitMessageFormat GetCommitMessageFormat (SolutionItem item) + public static CommitMessageFormat GetCommitMessageFormat (SolutionFolderItem item) { CommitMessageFormat format = new CommitMessageFormat (); format.Style = item.Policies.Get<VersionControlPolicy> ().CommitMessageStyle; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Task.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlTask.cs index 92aaac31c3..3ca1b9e2a5 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/Task.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl/VersionControlTask.cs @@ -6,9 +6,9 @@ using MonoDevelop.Core; namespace MonoDevelop.VersionControl { - internal abstract class Task + internal abstract class VersionControlTask { - IProgressMonitor tracker; + ProgressMonitor tracker; ThreadNotify threadnotify; protected VersionControlOperationType OperationType { get; set; } @@ -24,17 +24,17 @@ namespace MonoDevelop.VersionControl { } - protected Task() + protected VersionControlTask() { OperationType = VersionControlOperationType.Other; threadnotify = new ThreadNotify(new ReadyEvent(Wakeup)); } - protected IProgressMonitor Monitor { + protected ProgressMonitor Monitor { get { return tracker; } } - protected virtual IProgressMonitor CreateProgressMonitor () + protected virtual ProgressMonitor CreateProgressMonitor () { return VersionControlService.GetProgressMonitor (GetDescription (), OperationType); } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/VersionControl.addin.xml b/main/src/addins/VersionControl/MonoDevelop.VersionControl/VersionControl.addin.xml index 848fcc2200..18e0f0809b 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/VersionControl.addin.xml +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/VersionControl.addin.xml @@ -164,7 +164,7 @@ defaultHandler = "MonoDevelop.VersionControl.UnlockCommandHandler" description = "Unlock files in the repository, so that other user can change them."/> <Command id = "MonoDevelop.VersionControl.Commands.Annotate" - _label = "Show Annotations" + _label = "Blame" defaultHandler = "MonoDevelop.VersionControl.CurrentFileBlameHandler" description = "Show the origin of each line in a file."/> <Command id = "MonoDevelop.VersionControl.Commands.CreatePatch" diff --git a/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs b/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs index 667308fa8f..e7d8902ebc 100644 --- a/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs +++ b/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs @@ -41,14 +41,6 @@ namespace SubversionAddinWindows return new SvnSharpBackend ();
}
- public override string GetPathUrl (FilePath path)
- {
- lock (client) {
- Uri u = client.Value.GetUriFromWorkingCopy (path);
- return u != null ? u.ToString () : null;
- }
- }
-
public override bool IsInstalled
{
get
@@ -69,7 +61,8 @@ namespace SubversionAddinWindows {
string wc_path;
try {
- wc_path = client.Value.GetWorkingCopyRoot (path.FullPath);
+ lock (client.Value)
+ wc_path = client.Value.GetWorkingCopyRoot (path.FullPath);
return wc_path;
} catch (SvnException e) {
switch (e.SvnErrorCode) {
@@ -88,7 +81,7 @@ namespace SubversionAddinWindows get { return SvnSharpClient.client.Value; }
}
- IProgressMonitor updateMonitor;
+ ProgressMonitor updateMonitor;
NotifData notifyData;
ProgressData progressData;
@@ -98,7 +91,8 @@ namespace SubversionAddinWindows try {
// This outputs the contents of the base revision
// of a file to a stream.
- client.Write (new SvnPathTarget (sourcefile), data);
+ lock (client)
+ client.Write (new SvnPathTarget (sourcefile), data);
return TextFile.ReadFile (sourcefile, data).Text;
} catch (SvnIllegalTargetException e) {
// This occurs when we don't have a base file for
@@ -173,13 +167,14 @@ namespace SubversionAddinWindows SslFailure acceptedFailures;
bool save;
- var certInfo = new CertficateInfo ();
- certInfo.AsciiCert = e.CertificateValue;
- certInfo.Fingerprint = e.Fingerprint;
- certInfo.HostName = e.CommonName;
- certInfo.IssuerName = e.Issuer;
- certInfo.ValidFrom = e.ValidFrom;
- certInfo.ValidUntil = e.ValidUntil;
+ var certInfo = new CertficateInfo {
+ AsciiCert = e.CertificateValue,
+ Fingerprint = e.Fingerprint,
+ HostName = e.CommonName,
+ IssuerName = e.Issuer,
+ ValidFrom = e.ValidFrom,
+ ValidUntil = e.ValidUntil,
+ };
e.Cancel = !SslServerTrustAuthenticationPrompt (e.Realm, (SslFailure) (uint) e.Failures, e.MaySave, certInfo, out acceptedFailures, out save);
@@ -205,23 +200,25 @@ namespace SubversionAddinWindows e.CertificateFile = file;
}
- public override void Add (FilePath path, bool recurse, IProgressMonitor monitor)
+ public override void Add (FilePath path, bool recurse, ProgressMonitor monitor)
{
- var args = new SvnAddArgs ();
+ var args = new SvnAddArgs {
+ Depth = recurse ? SvnDepth.Infinity : SvnDepth.Empty,
+ };
BindMonitor (monitor);
- args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Empty;
lock (client)
client.Add (path, args);
}
- public override void Checkout (string url, FilePath path, Revision rev, bool recurse, IProgressMonitor monitor)
+ public override void Checkout (string url, FilePath path, Revision rev, bool recurse, ProgressMonitor monitor)
{
- var args = new SvnCheckOutArgs ();
+ var args = new SvnCheckOutArgs {
+ Depth = recurse ? SvnDepth.Infinity : SvnDepth.Empty,
+ };
BindMonitor (monitor);
- args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Empty;
lock (client) {
try {
- client.CheckOut (new SvnUriTarget (url, GetRevision (rev)), path);
+ client.CheckOut (new SvnUriTarget (url, GetRevision (rev)), path, args);
} catch (SvnOperationCanceledException) {
if (Directory.Exists (path.ParentDirectory))
FileService.DeleteDirectory (path.ParentDirectory);
@@ -229,20 +226,22 @@ namespace SubversionAddinWindows }
}
- public override void Commit (FilePath[] paths, string message, IProgressMonitor monitor)
+ public override void Commit (FilePath[] paths, string message, ProgressMonitor monitor)
{
- var args = new SvnCommitArgs ();
+ var args = new SvnCommitArgs {
+ LogMessage = message,
+ };
BindMonitor (monitor);
- args.LogMessage = message;
lock (client)
client.Commit (paths.ToStringArray (), args);
}
- public override void Delete (FilePath path, bool force, IProgressMonitor monitor)
+ public override void Delete (FilePath path, bool force, ProgressMonitor monitor)
{
- var args = new SvnDeleteArgs ();
+ var args = new SvnDeleteArgs {
+ Force = force,
+ };
BindMonitor (monitor);
- args.Force = force;
lock (client)
client.Delete (path, args);
}
@@ -250,7 +249,9 @@ namespace SubversionAddinWindows public override string GetTextAtRevision (string repositoryPath, Revision revision, string rootPath)
{
var ms = new MemoryStream ();
- SvnUriTarget target = client.GetUriFromWorkingCopy (rootPath);
+ SvnUriTarget target;
+ lock (client)
+ target = client.GetUriFromWorkingCopy (rootPath);
// Redo path link.
repositoryPath = repositoryPath.TrimStart (new [] { '/' });
foreach (var segment in target.Uri.Segments) {
@@ -279,7 +280,8 @@ namespace SubversionAddinWindows public override string GetVersion ()
{
- return SvnClient.Version.ToString ();
+ lock (client)
+ return SvnClient.Version.ToString ();
}
public override IEnumerable<DirectoryEntry> ListUrl (string url, bool recurse, SvnRevision rev)
@@ -292,41 +294,42 @@ namespace SubversionAddinWindows return List (new SvnPathTarget (path, GetRevision (rev)), recurse);
}
- IEnumerable<DirectoryEntry> List (SvnTarget target, bool recurse)
+ static IEnumerable<DirectoryEntry> List (SvnTarget target, bool recurse)
{
var list = new List<DirectoryEntry> ();
- var args = new SvnListArgs ();
- args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children;
+ var args = new SvnListArgs {
+ Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children,
+ };
lock (client)
client.List (target, args, delegate (object o, SvnListEventArgs a) {
- if (string.IsNullOrEmpty (a.Path))
- return;
- var de = new DirectoryEntry ();
- de.CreatedRevision = ToBaseRevision (a.Entry.Revision).Rev;
- de.HasProps = a.Entry.HasProperties;
- de.IsDirectory = a.Entry.NodeKind == SvnNodeKind.Directory;
- de.LastAuthor = a.Entry.Author;
- de.Name = a.Path;
- de.Size = a.Entry.FileSize;
- de.Time = a.Entry.Time;
- list.Add (de);
- });
+ if (string.IsNullOrEmpty (a.Path))
+ return;
+ list.Add (new DirectoryEntry {
+ CreatedRevision = ToBaseRevision (a.Entry.Revision).Rev,
+ HasProps = a.Entry.HasProperties,
+ IsDirectory = a.Entry.NodeKind == SvnNodeKind.Directory,
+ LastAuthor = a.Entry.Author,
+ Name = a.Path,
+ Size = a.Entry.FileSize,
+ Time = a.Entry.Time,
+ });
+ });
return list;
}
public override IEnumerable<SvnRevision> Log (Repository repo, FilePath path, SvnRevision revisionStart, SvnRevision revisionEnd)
{
var list = new List<SvnRevision> ();
- var args = new SvnLogArgs ();
- args.Range = new SvnRevisionRange (GetRevision (revisionStart), GetRevision (revisionEnd));
+ var args = new SvnLogArgs {
+ Range = new SvnRevisionRange (GetRevision (revisionStart), GetRevision (revisionEnd)),
+ };
lock (client)
client.Log (path, args, delegate (object o, SvnLogEventArgs a) {
var paths = new List<RevisionPath> ();
foreach (SvnChangeItem item in a.ChangedPaths) {
paths.Add (new RevisionPath (item.Path, ConvertRevisionAction (item.Action), ""));
}
- var r = new SvnRevision (repo, (int) a.Revision, a.Time, a.Author, a.LogMessage, paths.ToArray ());
- list.Add (r);
+ list.Add (new SvnRevision (repo, (int) a.Revision, a.Time, a.Author, a.LogMessage, paths.ToArray ()));
});
return list;
}
@@ -342,24 +345,26 @@ namespace SubversionAddinWindows return RevisionAction.Other;
}
- public override void Mkdir (string[] paths, string message, IProgressMonitor monitor)
+ public override void Mkdir (string[] paths, string message, ProgressMonitor monitor)
{
- var args = new SvnCreateDirectoryArgs ();
- args.CreateParents = true;
+ var args = new SvnCreateDirectoryArgs {
+ CreateParents = true,
+ LogMessage = message,
+ };
BindMonitor (monitor);
var uris = new List<Uri> ();
foreach (string path in paths)
uris.Add (new Uri (path));
- args.LogMessage = message;
lock (client)
client.RemoteCreateDirectories (uris, args);
}
- public override void Move (FilePath srcPath, FilePath destPath, SvnRevision rev, bool force, IProgressMonitor monitor)
+ public override void Move (FilePath srcPath, FilePath destPath, SvnRevision rev, bool force, ProgressMonitor monitor)
{
- var args = new SvnMoveArgs ();
+ var args = new SvnMoveArgs {
+ Force = force,
+ };
BindMonitor (monitor);
- args.Force = force;
lock (client)
client.Move (srcPath, destPath, args);
}
@@ -368,27 +373,30 @@ namespace SubversionAddinWindows {
var t1 = new SvnPathTarget (path1, GetRevision (revision1));
var t2 = new SvnPathTarget (path2, GetRevision (revision2));
- var args = new SvnDiffArgs ();
- args.Depth = recursive ? SvnDepth.Infinity : SvnDepth.Children;
- var ms = new MemoryStream ();
- lock (client)
- client.Diff (t1, t2, args, ms);
- ms.Position = 0;
- using (var sr = new StreamReader (ms)) {
- return sr.ReadToEnd ();
+ var args = new SvnDiffArgs {
+ Depth = recursive ? SvnDepth.Infinity : SvnDepth.Children,
+ };
+ using (var ms = new MemoryStream ()) {
+ lock (client)
+ client.Diff (t1, t2, args, ms);
+ ms.Position = 0;
+ using (var sr = new StreamReader (ms)) {
+ return sr.ReadToEnd ();
+ }
}
}
- public override void Revert (FilePath[] paths, bool recurse, IProgressMonitor monitor)
+ public override void Revert (FilePath[] paths, bool recurse, ProgressMonitor monitor)
{
- var args = new SvnRevertArgs ();
+ var args = new SvnRevertArgs {
+ Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children,
+ };
BindMonitor (monitor);
- args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children;
lock (client)
client.Revert (paths.ToStringArray (), args);
}
- public override void RevertRevision (FilePath path, Revision revision, IProgressMonitor monitor)
+ public override void RevertRevision (FilePath path, Revision revision, ProgressMonitor monitor)
{
var args = new SvnMergeArgs ();
BindMonitor (monitor);
@@ -398,7 +406,7 @@ namespace SubversionAddinWindows client.Merge (path, new SvnPathTarget (path), range, args);
}
- public override void RevertToRevision (FilePath path, Revision revision, IProgressMonitor monitor)
+ public override void RevertToRevision (FilePath path, Revision revision, ProgressMonitor monitor)
{
var args = new SvnMergeArgs ();
BindMonitor (monitor);
@@ -410,11 +418,12 @@ namespace SubversionAddinWindows public override IEnumerable<VersionInfo> Status (Repository repo, FilePath path, SvnRevision revision, bool descendDirs, bool changedItemsOnly, bool remoteStatus)
{
var list = new List<VersionInfo> ();
- var args = new SvnStatusArgs ();
- args.Revision = GetRevision (revision);
- args.Depth = descendDirs ? SvnDepth.Infinity : SvnDepth.Children;
- args.RetrieveAllEntries = !changedItemsOnly;
- args.RetrieveRemoteStatus = remoteStatus;
+ var args = new SvnStatusArgs {
+ Revision = GetRevision (revision),
+ Depth = descendDirs ? SvnDepth.Infinity : SvnDepth.Children,
+ RetrieveAllEntries = !changedItemsOnly,
+ RetrieveRemoteStatus = remoteStatus,
+ };
lock (client) {
try {
client.Status (path, args, (o, a) => list.Add (CreateVersionInfo (repo, a)));
@@ -497,31 +506,35 @@ namespace SubversionAddinWindows return VersionStatus.Unversioned;
}
- public override void Lock (IProgressMonitor monitor, string comment, bool stealLock, params FilePath[] paths)
+ public override void Lock (ProgressMonitor monitor, string comment, bool stealLock, params FilePath[] paths)
{
- var args = new SvnLockArgs ();
+ var args = new SvnLockArgs {
+ Comment = comment,
+ StealLock = stealLock,
+ };
BindMonitor (monitor);
- args.Comment = comment;
- args.StealLock = stealLock;
lock (client)
client.Lock (paths.ToStringArray (), args);
}
- public override void Unlock (IProgressMonitor monitor, bool breakLock, params FilePath[] paths)
+ public override void Unlock (ProgressMonitor monitor, bool breakLock, params FilePath[] paths)
{
- var args = new SvnUnlockArgs ();
+ var args = new SvnUnlockArgs {
+ BreakLock = breakLock,
+ };
BindMonitor (monitor);
- args.BreakLock = breakLock;
lock (client)
client.Unlock (paths.ToStringArray (), args);
}
- public override void Update (FilePath path, bool recurse, IProgressMonitor monitor)
+ public override void Update (FilePath path, bool recurse, ProgressMonitor monitor)
{
- var args = new SvnUpdateArgs ();
+ var args = new SvnUpdateArgs {
+ Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children,
+ };
BindMonitor (monitor);
- args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children;
- client.Update (path, args);
+ lock (client)
+ client.Update (path, args);
}
public override void Ignore (FilePath[] paths)
@@ -556,22 +569,29 @@ namespace SubversionAddinWindows throw new ArgumentNullException ();
var target = new SvnPathTarget (file, SharpSvn.SvnRevision.Base);
- var data = new MemoryStream ();
int numAnnotations = 0;
- client.Write (target, data);
-
- using (var reader = new StreamReader (data)) {
- reader.BaseStream.Seek (0, SeekOrigin.Begin);
- while (reader.ReadLine () != null)
- numAnnotations++;
+ using (var data = new MemoryStream ()) {
+ lock (client)
+ client.Write (target, data);
+
+ using (var reader = new StreamReader (data)) {
+ reader.BaseStream.Seek (0, SeekOrigin.Begin);
+ while (reader.ReadLine () != null)
+ numAnnotations++;
+ }
}
System.Collections.ObjectModel.Collection<SvnBlameEventArgs> list;
- var args = new SvnBlameArgs ();
- args.Start = GetRevision (revStart);
- args.End = GetRevision (revEnd);
+ var args = new SvnBlameArgs {
+ Start = GetRevision (revStart),
+ End = GetRevision (revEnd),
+ };
- if (client.GetBlame (target, args, out list)) {
+ bool success;
+ lock (client) {
+ success = client.GetBlame (target, args, out list);
+ }
+ if (success) {
var annotations = new Annotation [numAnnotations];
foreach (var annotation in list) {
if (annotation.LineNumber < annotations.Length)
@@ -633,7 +653,7 @@ namespace SubversionAddinWindows public int Seconds;
}
- void BindMonitor (IProgressMonitor monitor)
+ void BindMonitor (ProgressMonitor monitor)
{
notifyData = new NotifData ();
progressData = new ProgressData ();
@@ -648,7 +668,7 @@ namespace SubversionAddinWindows return String.Format ("{0:0.00} MBytes", kbytes / 1024.0);
}
- static void ProgressWork (SvnProgressEventArgs e, ProgressData data, IProgressMonitor monitor)
+ static void ProgressWork (SvnProgressEventArgs e, ProgressData data, ProgressMonitor monitor)
{
if (monitor == null)
return;
@@ -685,7 +705,7 @@ namespace SubversionAddinWindows data.LogTimer.Start ();
}
- static void Notify (SvnNotifyEventArgs e, NotifData notifData, IProgressMonitor monitor)
+ static void Notify (SvnNotifyEventArgs e, NotifData notifData, ProgressMonitor monitor)
{
string actiondesc;
string file = e.Path;
diff --git a/main/src/addins/VersionControl/Subversion.Win32/VersionControl.Subversion.Win32.csproj b/main/src/addins/VersionControl/Subversion.Win32/VersionControl.Subversion.Win32.csproj index d635660a89..5a78c6eb76 100644 --- a/main/src/addins/VersionControl/Subversion.Win32/VersionControl.Subversion.Win32.csproj +++ b/main/src/addins/VersionControl/Subversion.Win32/VersionControl.Subversion.Win32.csproj @@ -59,8 +59,11 @@ </PropertyGroup> <ItemGroup> <Reference Include="System" /> - <Reference Include="SharpSvn, Version=1.8005.2778.15501, Culture=neutral, PublicKeyToken=d729672594885a28"> - <HintPath>..\..\..\..\external\sharpsvn-binary\SharpSvn.dll</HintPath> + <Reference Include="SharpSvn"> + <HintPath>..\..\..\..\packages\SharpSvn.1.8-x86.1.8010.3345.53\lib\net40\SharpSvn.dll</HintPath> + </Reference> + <Reference Include="SharpSvn.UI"> + <HintPath>..\..\..\..\packages\SharpSvn.1.8-x86.1.8010.3345.53\lib\net40\SharpSvn.UI.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> @@ -89,13 +92,13 @@ </BootstrapperPackage> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> - <!-- To modify your build process, add your task inside one of the targets below and uncomment it. - Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> + <PropertyGroup> + <NuGet>$(SolutionDir)\external\nuget-binary\NuGet.exe</NuGet> + <NuGet Condition="$(OS)=='Unix'">mono $(NuGet)</NuGet> + </PropertyGroup> + <Exec Command="$(NuGet) restore -SolutionDirectory $(SolutionDir)" /> </Target> - <Target Name="AfterBuild"> - </Target> - --> <ItemGroup> <ProjectReference Include="..\..\..\core\MonoDevelop.Core\MonoDevelop.Core.csproj"> <Project>{7525BB88-6142-4A26-93B9-A30C6983390A}</Project> @@ -124,13 +127,14 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <None Include="..\..\..\..\external\sharpsvn-binary\SharpPlink-Win32.svnExe"> + <None Include="..\..\..\..\packages\SharpSvn.1.8-x86.1.8010.3345.53\lib\net40\SharpPlink-Win32.svnExe"> <Link>SharpPlink-Win32.svnExe</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> - <None Include="..\..\..\..\external\sharpsvn-binary\SharpSvn-DB44-20-win32.svnDll"> + <None Include="..\..\..\..\packages\SharpSvn.1.8-x86.1.8010.3345.53\lib\net40\SharpSvn-DB44-20-win32.svnDll"> <Link>SharpSvn-DB44-20-win32.svnDll</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> + <None Include="packages.config" /> </ItemGroup> </Project>
\ No newline at end of file diff --git a/main/src/addins/VersionControl/Subversion.Win32/packages.config b/main/src/addins/VersionControl/Subversion.Win32/packages.config new file mode 100644 index 0000000000..eead751a62 --- /dev/null +++ b/main/src/addins/VersionControl/Subversion.Win32/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?>
+<packages>
+ <package id="SharpSvn.1.8-x86" version="1.8010.3345.53" targetFramework="net40" />
+</packages>
\ No newline at end of file diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform/Dialogs/OpenFileDialogHandler.cs b/main/src/addins/WindowsPlatform/WindowsPlatform/Dialogs/OpenFileDialogHandler.cs index 068c0f69e6..5c548b0128 100644 --- a/main/src/addins/WindowsPlatform/WindowsPlatform/Dialogs/OpenFileDialogHandler.cs +++ b/main/src/addins/WindowsPlatform/WindowsPlatform/Dialogs/OpenFileDialogHandler.cs @@ -47,8 +47,6 @@ namespace MonoDevelop.Platform {
public class OpenFileDialogHandler : IOpenFileDialogHandler
{
- static int[] encodings;
-
public bool Run (OpenFileDialogData data)
{
var parent = data.TransientFor ?? MessageService.RootWindow;
@@ -96,6 +94,7 @@ namespace MonoDevelop.Platform dialog.Controls.Add (group);
if (IdeApp.Workspace.IsOpen) {
+ viewerCombo.SelectedIndexChanged += (o, e) => closeSolution.Visible = ((ViewerComboItem)viewerCombo.Items[viewerCombo.SelectedIndex]).Viewer == null;
var group2 = new CommonFileDialogGroupBox ();
// "Close current workspace" is too long and splits the text on 2 lines.
@@ -130,7 +129,9 @@ namespace MonoDevelop.Platform if (viewerCombo != null) {
if (closeSolution != null)
data.CloseCurrentWorkspace = closeSolution.Visible && closeSolution.IsChecked;
- data.SelectedViewer = ((ViewerComboItem)viewerCombo.Items [viewerCombo.SelectedIndex]).Viewer;
+ int index = viewerCombo.SelectedIndex;
+ if (index != -1)
+ data.SelectedViewer = ((ViewerComboItem)viewerCombo.Items [index]).Viewer;
}
return true;
@@ -173,39 +174,35 @@ namespace MonoDevelop.Platform int i = 0;
if (showAutoDetected) {
- combo.Items.Add (new EncodingComboItem (-1, GettextCatalog.GetString ("Auto Detected")));
+ combo.Items.Add (new EncodingComboItem (null, GettextCatalog.GetString ("Auto Detected")));
combo.SelectedIndex = 0;
i = 1;
}
- encodings = SelectedEncodings.ConversionEncodings;
- if (encodings == null || encodings.Length == 0)
- encodings = SelectedEncodings.DefaultEncodings;
-
int j = 1;
foreach (var e in TextEncoding.ConversionEncodings) {
- combo.Items.Add (new EncodingComboItem (j++, string.Format ("{0} ({1})", e.Name, e.Id)));
+ combo.Items.Add (new EncodingComboItem (Encoding.GetEncoding (e.CodePage), string.Format ("{0} ({1})", e.Name, e.Id)));
if (selectedEncoding != null && e.CodePage == selectedEncoding.WindowsCodePage)
combo.SelectedIndex = i;
i++;
}
if (combo.SelectedIndex == -1)
combo.SelectedIndex = 0;
- combo.Items.Add (new EncodingComboItem (-1, GettextCatalog.GetString ("Add or Remove...")));
+ combo.Items.Add (new EncodingComboItem (null, GettextCatalog.GetString ("Add or Remove...")));
}
class EncodingComboItem : CommonFileDialogComboBoxItem
{
- int tag;
+ Encoding encoding;
- public EncodingComboItem (int tag, string label) : base (label)
+ public EncodingComboItem (Encoding encoding, string label) : base (label)
{
- this.tag = tag;
+ this.encoding = encoding;
}
public Encoding Encoding {
get {
- return tag <= 0 ? null : Encoding.GetEncoding (encodings [tag - 1]);
+ return encoding;
}
}
}
diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform/Enums.cs b/main/src/addins/WindowsPlatform/WindowsPlatform/Enums.cs deleted file mode 100644 index 489c9def44..0000000000 --- a/main/src/addins/WindowsPlatform/WindowsPlatform/Enums.cs +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright (c) 2006, Gustavo Franco
-// Email: gustavo_franco@hotmail.com
-// All rights reserved.
-
-// Redistribution and use in source and binary forms, with or without modification,
-// are permitted provided that the following conditions are met:
-
-// Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following disclaimer in the documentation
-// and/or other materials provided with the distribution.
-
-// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
-// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
-// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
-// REMAINS UNCHANGED.
-
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Runtime.InteropServices;
-
-namespace CustomControls.OS
-{
- #region SWP_Flags
- [Flags]
- public enum SWP_Flags
- {
- SWP_NOSIZE = 0x0001,
- SWP_NOMOVE = 0x0002,
- SWP_NOZORDER = 0x0004,
- SWP_NOACTIVATE = 0x0010,
- SWP_FRAMECHANGED = 0x0020, /* The frame changed: send WM_NCCALCSIZE */
- SWP_SHOWWINDOW = 0x0040,
- SWP_HIDEWINDOW = 0x0080,
- SWP_NOOWNERZORDER = 0x0200, /* Don't do owner Z ordering */
-
- SWP_DRAWFRAME = SWP_FRAMECHANGED,
- SWP_NOREPOSITION = SWP_NOOWNERZORDER
- }
- #endregion
-
- #region DialogChangeStatus
- public enum DialogChangeStatus : long
- {
- CDN_FIRST = 0xFFFFFDA7,
- CDN_INITDONE = (CDN_FIRST - 0x0000),
- CDN_SELCHANGE = (CDN_FIRST - 0x0001),
- CDN_FOLDERCHANGE = (CDN_FIRST - 0x0002),
- CDN_SHAREVIOLATION = (CDN_FIRST - 0x0003),
- CDN_HELP = (CDN_FIRST - 0x0004),
- CDN_FILEOK = (CDN_FIRST - 0x0005),
- CDN_TYPECHANGE = (CDN_FIRST - 0x0006),
- }
- #endregion
-
- #region DialogChangeProperties
- public enum DialogChangeProperties
- {
- CDM_FIRST = (0x400 + 100),
- CDM_GETSPEC = (CDM_FIRST + 0x0000),
- CDM_GETFILEPATH = (CDM_FIRST + 0x0001),
- CDM_GETFOLDERPATH = (CDM_FIRST + 0x0002),
- CDM_GETFOLDERIDLIST = (CDM_FIRST + 0x0003),
- CDM_SETCONTROLTEXT = (CDM_FIRST + 0x0004),
- CDM_HIDECONTROL = (CDM_FIRST + 0x0005),
- CDM_SETDEFEXT = (CDM_FIRST + 0x0006)
- }
- #endregion
-
- #region ImeNotify
- [Author("Franco, Gustavo")]
- public enum ImeNotify
- {
- IMN_CLOSESTATUSWINDOW = 0x0001,
- IMN_OPENSTATUSWINDOW = 0x0002,
- IMN_CHANGECANDIDATE = 0x0003,
- IMN_CLOSECANDIDATE = 0x0004,
- IMN_OPENCANDIDATE = 0x0005,
- IMN_SETCONVERSIONMODE = 0x0006,
- IMN_SETSENTENCEMODE = 0x0007,
- IMN_SETOPENSTATUS = 0x0008,
- IMN_SETCANDIDATEPOS = 0x0009,
- IMN_SETCOMPOSITIONFONT = 0x000A,
- IMN_SETCOMPOSITIONWINDOW = 0x000B,
- IMN_SETSTATUSWINDOWPOS = 0x000C,
- IMN_GUIDELINE = 0x000D,
- IMN_PRIVATE = 0x000E
- }
- #endregion
-
- #region FolderViewMode
- [Author("Franco, Gustavo")]
- public enum FolderViewMode
- {
- Default = 0x7028,
- Icon = Default + 1,
- SmallIcon = Default + 2,
- List = Default + 3,
- Details = Default + 4,
- Thumbnails = Default + 5,
- Title = Default + 6,
- Thumbstrip = Default + 7,
- }
- #endregion
-
- #region Enum DialogViewProperty
- [Author("Franco, Gustavo")]
- public enum DefaultViewType
- {
- Icons = 0x7029,
- List = 0x702b,
- Details = 0x702c,
- Thumbnails = 0x702d,
- Tiles = 0x702e,
- }
- #endregion
-
- #region ButtonStyle
- [Author("Franco, Gustavo")]
- public enum ButtonStyle : long
- {
- BS_PUSHBUTTON = 0x00000000,
- BS_DEFPUSHBUTTON = 0x00000001,
- BS_CHECKBOX = 0x00000002,
- BS_AUTOCHECKBOX = 0x00000003,
- BS_RADIOBUTTON = 0x00000004,
- BS_3STATE = 0x00000005,
- BS_AUTO3STATE = 0x00000006,
- BS_GROUPBOX = 0x00000007,
- BS_USERBUTTON = 0x00000008,
- BS_AUTORADIOBUTTON= 0x00000009,
- BS_PUSHBOX = 0x0000000A,
- BS_OWNERDRAW = 0x0000000B,
- BS_TYPEMASK = 0x0000000F,
- BS_LEFTTEXT = 0x00000020,
- BS_TEXT = 0x00000000,
- BS_ICON = 0x00000040,
- BS_BITMAP = 0x00000080,
- BS_LEFT = 0x00000100,
- BS_RIGHT = 0x00000200,
- BS_CENTER = 0x00000300,
- BS_TOP = 0x00000400,
- BS_BOTTOM = 0x00000800,
- BS_VCENTER = 0x00000C00,
- BS_PUSHLIKE = 0x00001000,
- BS_MULTILINE = 0x00002000,
- BS_NOTIFY = 0x00004000,
- BS_FLAT = 0x00008000,
- BS_RIGHTBUTTON = BS_LEFTTEXT
- }
- #endregion
-
- #region ZOrderPos
- [Author("Franco, Gustavo")]
- public enum ZOrderPos
- {
- HWND_TOP = 0,
- HWND_BOTTOM = 1,
- HWND_TOPMOST = -1,
- HWND_NOTOPMOST = -2
- }
- #endregion
-
- #region Static Control Styles
- [Author("Franco, Gustavo")]
- public enum StaticControlStyles : long
- {
- SS_LEFT = 0x00000000,
- SS_CENTER = 0x00000001,
- SS_RIGHT = 0x00000002,
- SS_ICON = 0x00000003,
- SS_BLACKRECT = 0x00000004,
- SS_GRAYRECT = 0x00000005,
- SS_WHITERECT = 0x00000006,
- SS_BLACKFRAME = 0x00000007,
- SS_GRAYFRAME = 0x00000008,
- SS_WHITEFRAME = 0x00000009,
- SS_USERITEM = 0x0000000A,
- SS_SIMPLE = 0x0000000B,
- SS_LEFTNOWORDWRAP = 0x0000000C,
- SS_OWNERDRAW = 0x0000000D,
- SS_BITMAP = 0x0000000E,
- SS_ENHMETAFILE = 0x0000000F,
- SS_ETCHEDHORZ = 0x00000010,
- SS_ETCHEDVERT = 0x00000011,
- SS_ETCHEDFRAME = 0x00000012,
- SS_TYPEMASK = 0x0000001F,
- SS_REALSIZECONTROL = 0x00000040,
- SS_NOPREFIX = 0x00000080, /* Don't do "&" character translation */
- SS_NOTIFY = 0x00000100,
- SS_CENTERIMAGE = 0x00000200,
- SS_RIGHTJUST = 0x00000400,
- SS_REALSIZEIMAGE = 0x00000800,
- SS_SUNKEN = 0x00001000,
- SS_EDITCONTROL = 0x00002000,
- SS_ENDELLIPSIS = 0x00004000,
- SS_PATHELLIPSIS = 0x00008000,
- SS_WORDELLIPSIS = 0x0000C000,
- SS_ELLIPSISMASK = 0x0000C000
- }
- #endregion
-
- #region Combo Box styles
- [Author("Franco, Gustavo")]
- public enum ComboBoxStyles : long
- {
- CBS_SIMPLE = 0x0001,
- CBS_DROPDOWN = 0x0002,
- CBS_DROPDOWNLIST = 0x0003,
- CBS_OWNERDRAWFIXED = 0x0010,
- CBS_OWNERDRAWVARIABLE = 0x0020,
- CBS_AUTOHSCROLL = 0x0040,
- CBS_OEMCONVERT = 0x0080,
- CBS_SORT = 0x0100,
- CBS_HASSTRINGS = 0x0200,
- CBS_NOINTEGRALHEIGHT = 0x0400,
- CBS_DISABLENOSCROLL = 0x0800,
- CBS_UPPERCASE = 0x2000,
- CBS_LOWERCASE = 0x4000
- }
- #endregion
-
- #region Window Styles
- [Author("Franco, Gustavo")]
- public enum WindowStyles : long
- {
- WS_OVERLAPPED = 0x00000000,
- WS_POPUP = 0x80000000,
- WS_CHILD = 0x40000000,
- WS_MINIMIZE = 0x20000000,
- WS_VISIBLE = 0x10000000,
- WS_DISABLED = 0x08000000,
- WS_CLIPSIBLINGS = 0x04000000,
- WS_CLIPCHILDREN = 0x02000000,
- WS_MAXIMIZE = 0x01000000,
- WS_CAPTION = 0x00C00000,
- WS_BORDER = 0x00800000,
- WS_DLGFRAME = 0x00400000,
- WS_VSCROLL = 0x00200000,
- WS_HSCROLL = 0x00100000,
- WS_SYSMENU = 0x00080000,
- WS_THICKFRAME = 0x00040000,
- WS_GROUP = 0x00020000,
- WS_TABSTOP = 0x00010000,
- WS_MINIMIZEBOX = 0x00020000,
- WS_MAXIMIZEBOX = 0x00010000,
- WS_TILED = 0x00000000,
- WS_ICONIC = 0x20000000,
- WS_SIZEBOX = 0x00040000,
- WS_POPUPWINDOW = 0x80880000,
- WS_OVERLAPPEDWINDOW = 0x00CF0000,
- WS_TILEDWINDOW = 0x00CF0000,
- WS_CHILDWINDOW = 0x40000000
- }
- #endregion
-
- #region Window Extended Styles
- [Author("Franco, Gustavo")]
- [Flags]
- public enum WindowExStyles
- {
- WS_EX_DLGMODALFRAME = 0x00000001,
- WS_EX_NOPARENTNOTIFY = 0x00000004,
- WS_EX_TOPMOST = 0x00000008,
- WS_EX_ACCEPTFILES = 0x00000010,
- WS_EX_TRANSPARENT = 0x00000020,
- WS_EX_MDICHILD = 0x00000040,
- WS_EX_TOOLWINDOW = 0x00000080,
- WS_EX_WINDOWEDGE = 0x00000100,
- WS_EX_CLIENTEDGE = 0x00000200,
- WS_EX_CONTEXTHELP = 0x00000400,
- WS_EX_RIGHT = 0x00001000,
- WS_EX_LEFT = 0x00000000,
- WS_EX_RTLREADING = 0x00002000,
- WS_EX_LTRREADING = 0x00000000,
- WS_EX_LEFTSCROLLBAR = 0x00004000,
- WS_EX_RIGHTSCROLLBAR = 0x00000000,
- WS_EX_CONTROLPARENT = 0x00010000,
- WS_EX_STATICEDGE = 0x00020000,
- WS_EX_APPWINDOW = 0x00040000,
- WS_EX_OVERLAPPEDWINDOW = 0x00000300,
- WS_EX_PALETTEWINDOW = 0x00000188,
- WS_EX_LAYERED = 0x00080000
- }
- #endregion
-
- #region ChildFromPointFlags
- [Author("Franco, Gustavo")]
- public enum ChildFromPointFlags
- {
- CWP_ALL = 0x0000,
- CWP_SKIPINVISIBLE = 0x0001,
- CWP_SKIPDISABLED = 0x0002,
- CWP_SKIPTRANSPARENT = 0x0004
- }
- #endregion
-
- #region HitTest
- [Author("Franco, Gustavo")]
- public enum HitTest
- {
- HTERROR = (-2),
- HTTRANSPARENT = (-1),
- HTNOWHERE = 0,
- HTCLIENT = 1,
- HTCAPTION = 2,
- HTSYSMENU = 3,
- HTGROWBOX = 4,
- HTSIZE = HTGROWBOX,
- HTMENU = 5,
- HTHSCROLL = 6,
- HTVSCROLL = 7,
- HTMINBUTTON = 8,
- HTMAXBUTTON = 9,
- HTLEFT = 10,
- HTRIGHT = 11,
- HTTOP = 12,
- HTTOPLEFT = 13,
- HTTOPRIGHT = 14,
- HTBOTTOM = 15,
- HTBOTTOMLEFT = 16,
- HTBOTTOMRIGHT = 17,
- HTBORDER = 18,
- HTREDUCE = HTMINBUTTON,
- HTZOOM = HTMAXBUTTON,
- HTSIZEFIRST = HTLEFT,
- HTSIZELAST = HTBOTTOMRIGHT,
- HTOBJECT = 19,
- HTCLOSE = 20,
- HTHELP = 21
- }
- #endregion
-
- #region Windows Messages
- [Author("Franco, Gustavo")]
- public enum Msg
- {
- WM_NULL = 0x0000,
- WM_CREATE = 0x0001,
- WM_DESTROY = 0x0002,
- WM_MOVE = 0x0003,
- WM_SIZE = 0x0005,
- WM_ACTIVATE = 0x0006,
- WM_SETFOCUS = 0x0007,
- WM_KILLFOCUS = 0x0008,
- WM_ENABLE = 0x000A,
- WM_SETREDRAW = 0x000B,
- WM_SETTEXT = 0x000C,
- WM_GETTEXT = 0x000D,
- WM_GETTEXTLENGTH = 0x000E,
- WM_PAINT = 0x000F,
- WM_CLOSE = 0x0010,
- WM_QUERYENDSESSION = 0x0011,
- WM_QUIT = 0x0012,
- WM_QUERYOPEN = 0x0013,
- WM_ERASEBKGND = 0x0014,
- WM_SYSCOLORCHANGE = 0x0015,
- WM_ENDSESSION = 0x0016,
- WM_SHOWWINDOW = 0x0018,
- WM_CTLCOLOR = 0x0019,
- WM_WININICHANGE = 0x001A,
- WM_SETTINGCHANGE = 0x001A,
- WM_DEVMODECHANGE = 0x001B,
- WM_ACTIVATEAPP = 0x001C,
- WM_FONTCHANGE = 0x001D,
- WM_TIMECHANGE = 0x001E,
- WM_CANCELMODE = 0x001F,
- WM_SETCURSOR = 0x0020,
- WM_MOUSEACTIVATE = 0x0021,
- WM_CHILDACTIVATE = 0x0022,
- WM_QUEUESYNC = 0x0023,
- WM_GETMINMAXINFO = 0x0024,
- WM_PAINTICON = 0x0026,
- WM_ICONERASEBKGND = 0x0027,
- WM_NEXTDLGCTL = 0x0028,
- WM_SPOOLERSTATUS = 0x002A,
- WM_DRAWITEM = 0x002B,
- WM_MEASUREITEM = 0x002C,
- WM_DELETEITEM = 0x002D,
- WM_VKEYTOITEM = 0x002E,
- WM_CHARTOITEM = 0x002F,
- WM_SETFONT = 0x0030,
- WM_GETFONT = 0x0031,
- WM_SETHOTKEY = 0x0032,
- WM_GETHOTKEY = 0x0033,
- WM_QUERYDRAGICON = 0x0037,
- WM_COMPAREITEM = 0x0039,
- WM_GETOBJECT = 0x003D,
- WM_COMPACTING = 0x0041,
- WM_COMMNOTIFY = 0x0044 ,
- WM_WINDOWPOSCHANGING = 0x0046,
- WM_WINDOWPOSCHANGED = 0x0047,
- WM_POWER = 0x0048,
- WM_COPYDATA = 0x004A,
- WM_CANCELJOURNAL = 0x004B,
- WM_NOTIFY = 0x004E,
- WM_INPUTLANGCHANGEREQUEST = 0x0050,
- WM_INPUTLANGCHANGE = 0x0051,
- WM_TCARD = 0x0052,
- WM_HELP = 0x0053,
- WM_USERCHANGED = 0x0054,
- WM_NOTIFYFORMAT = 0x0055,
- WM_CONTEXTMENU = 0x007B,
- WM_STYLECHANGING = 0x007C,
- WM_STYLECHANGED = 0x007D,
- WM_DISPLAYCHANGE = 0x007E,
- WM_GETICON = 0x007F,
- WM_SETICON = 0x0080,
- WM_NCCREATE = 0x0081,
- WM_NCDESTROY = 0x0082,
- WM_NCCALCSIZE = 0x0083,
- WM_NCHITTEST = 0x0084,
- WM_NCPAINT = 0x0085,
- WM_NCACTIVATE = 0x0086,
- WM_GETDLGCODE = 0x0087,
- WM_SYNCPAINT = 0x0088,
- WM_NCMOUSEMOVE = 0x00A0,
- WM_NCLBUTTONDOWN = 0x00A1,
- WM_NCLBUTTONUP = 0x00A2,
- WM_NCLBUTTONDBLCLK = 0x00A3,
- WM_NCRBUTTONDOWN = 0x00A4,
- WM_NCRBUTTONUP = 0x00A5,
- WM_NCRBUTTONDBLCLK = 0x00A6,
- WM_NCMBUTTONDOWN = 0x00A7,
- WM_NCMBUTTONUP = 0x00A8,
- WM_NCMBUTTONDBLCLK = 0x00A9,
- WM_NCXBUTTONDOWN = 0x00AB,
- WM_NCXBUTTONUP = 0x00AC,
- WM_NCXBUTTONDBLCLK = 0x00AD,
- WM_KEYDOWN = 0x0100,
- WM_KEYUP = 0x0101,
- WM_CHAR = 0x0102,
- WM_DEADCHAR = 0x0103,
- WM_SYSKEYDOWN = 0x0104,
- WM_SYSKEYUP = 0x0105,
- WM_SYSCHAR = 0x0106,
- WM_SYSDEADCHAR = 0x0107,
- WM_KEYLAST = 0x0108,
- WM_IME_STARTCOMPOSITION = 0x010D,
- WM_IME_ENDCOMPOSITION = 0x010E,
- WM_IME_COMPOSITION = 0x010F,
- WM_IME_KEYLAST = 0x010F,
- WM_INITDIALOG = 0x0110,
- WM_COMMAND = 0x0111,
- WM_SYSCOMMAND = 0x0112,
- WM_TIMER = 0x0113,
- WM_HSCROLL = 0x0114,
- WM_VSCROLL = 0x0115,
- WM_INITMENU = 0x0116,
- WM_INITMENUPOPUP = 0x0117,
- WM_MENUSELECT = 0x011F,
- WM_MENUCHAR = 0x0120,
- WM_ENTERIDLE = 0x0121,
- WM_MENURBUTTONUP = 0x0122,
- WM_MENUDRAG = 0x0123,
- WM_MENUGETOBJECT = 0x0124,
- WM_UNINITMENUPOPUP = 0x0125,
- WM_MENUCOMMAND = 0x0126,
- WM_CTLCOLORMSGBOX = 0x0132,
- WM_CTLCOLOREDIT = 0x0133,
- WM_CTLCOLORLISTBOX = 0x0134,
- WM_CTLCOLORBTN = 0x0135,
- WM_CTLCOLORDLG = 0x0136,
- WM_CTLCOLORSCROLLBAR = 0x0137,
- WM_CTLCOLORSTATIC = 0x0138,
- WM_MOUSEMOVE = 0x0200,
- WM_LBUTTONDOWN = 0x0201,
- WM_LBUTTONUP = 0x0202,
- WM_LBUTTONDBLCLK = 0x0203,
- WM_RBUTTONDOWN = 0x0204,
- WM_RBUTTONUP = 0x0205,
- WM_RBUTTONDBLCLK = 0x0206,
- WM_MBUTTONDOWN = 0x0207,
- WM_MBUTTONUP = 0x0208,
- WM_MBUTTONDBLCLK = 0x0209,
- WM_MOUSEWHEEL = 0x020A,
- WM_XBUTTONDOWN = 0x020B,
- WM_XBUTTONUP = 0x020C,
- WM_XBUTTONDBLCLK = 0x020D,
- WM_PARENTNOTIFY = 0x0210,
- WM_ENTERMENULOOP = 0x0211,
- WM_EXITMENULOOP = 0x0212,
- WM_NEXTMENU = 0x0213,
- WM_SIZING = 0x0214,
- WM_CAPTURECHANGED = 0x0215,
- WM_MOVING = 0x0216,
- WM_DEVICECHANGE = 0x0219,
- WM_MDICREATE = 0x0220,
- WM_MDIDESTROY = 0x0221,
- WM_MDIACTIVATE = 0x0222,
- WM_MDIRESTORE = 0x0223,
- WM_MDINEXT = 0x0224,
- WM_MDIMAXIMIZE = 0x0225,
- WM_MDITILE = 0x0226,
- WM_MDICASCADE = 0x0227,
- WM_MDIICONARRANGE = 0x0228,
- WM_MDIGETACTIVE = 0x0229,
- WM_MDISETMENU = 0x0230,
- WM_ENTERSIZEMOVE = 0x0231,
- WM_EXITSIZEMOVE = 0x0232,
- WM_DROPFILES = 0x0233,
- WM_MDIREFRESHMENU = 0x0234,
- WM_IME_SETCONTEXT = 0x0281,
- WM_IME_NOTIFY = 0x0282,
- WM_IME_CONTROL = 0x0283,
- WM_IME_COMPOSITIONFULL = 0x0284,
- WM_IME_SELECT = 0x0285,
- WM_IME_CHAR = 0x0286,
- WM_IME_REQUEST = 0x0288,
- WM_IME_KEYDOWN = 0x0290,
- WM_IME_KEYUP = 0x0291,
- WM_MOUSEHOVER = 0x02A1,
- WM_MOUSELEAVE = 0x02A3,
- WM_CUT = 0x0300,
- WM_COPY = 0x0301,
- WM_PASTE = 0x0302,
- WM_CLEAR = 0x0303,
- WM_UNDO = 0x0304,
- WM_RENDERFORMAT = 0x0305,
- WM_RENDERALLFORMATS = 0x0306,
- WM_DESTROYCLIPBOARD = 0x0307,
- WM_DRAWCLIPBOARD = 0x0308,
- WM_PAINTCLIPBOARD = 0x0309,
- WM_VSCROLLCLIPBOARD = 0x030A,
- WM_SIZECLIPBOARD = 0x030B,
- WM_ASKCBFORMATNAME = 0x030C,
- WM_CHANGECBCHAIN = 0x030D,
- WM_HSCROLLCLIPBOARD = 0x030E,
- WM_QUERYNEWPALETTE = 0x030F,
- WM_PALETTEISCHANGING = 0x0310,
- WM_PALETTECHANGED = 0x0311,
- WM_HOTKEY = 0x0312,
- WM_PRINT = 0x0317,
- WM_PRINTCLIENT = 0x0318,
- WM_THEME_CHANGED = 0x031A,
- WM_HANDHELDFIRST = 0x0358,
- WM_HANDHELDLAST = 0x035F,
- WM_AFXFIRST = 0x0360,
- WM_AFXLAST = 0x037F,
- WM_PENWINFIRST = 0x0380,
- WM_PENWINLAST = 0x038F,
- WM_APP = 0x8000,
- WM_USER = 0x0400,
- WM_REFLECT = WM_USER + 0x1c00
- }
- #endregion
-
- #region SetWindowPosFlags
- [Author("Franco, Gustavo")]
- [Flags]
- public enum SetWindowPosFlags
- {
- SWP_NOSIZE = 0x0001,
- SWP_NOMOVE = 0x0002,
- SWP_NOZORDER = 0x0004,
- SWP_NOREDRAW = 0x0008,
- SWP_NOACTIVATE = 0x0010,
- SWP_FRAMECHANGED = 0x0020,
- SWP_SHOWWINDOW = 0x0040,
- SWP_HIDEWINDOW = 0x0080,
- SWP_NOCOPYBITS = 0x0100,
- SWP_NOOWNERZORDER = 0x0200,
- SWP_NOSENDCHANGING = 0x0400,
- SWP_DRAWFRAME = 0x0020,
- SWP_NOREPOSITION = 0x0200,
- SWP_DEFERERASE = 0x2000,
- SWP_ASYNCWINDOWPOS = 0x4000
- }
- #endregion
-}
diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform/JumpList.cs b/main/src/addins/WindowsPlatform/WindowsPlatform/JumpList.cs index 3a3a442a92..d2baeebf3e 100644 --- a/main/src/addins/WindowsPlatform/WindowsPlatform/JumpList.cs +++ b/main/src/addins/WindowsPlatform/WindowsPlatform/JumpList.cs @@ -128,7 +128,7 @@ namespace MonoDevelop.Platform continue;
}
- RegistryKey openWithKey = Registry.ClassesRoot.OpenSubKey (Path.Combine (subkey, "OpenWithProgIds"));
+ RegistryKey openWithKey = Registry.ClassesRoot.OpenSubKey (Path.Combine (subkey, "OpenWithProgids"));
if (openWithKey == null) {
continue;
}
diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform/Win32.cs b/main/src/addins/WindowsPlatform/WindowsPlatform/Win32.cs index d6a21f261e..b6476ea979 100644 --- a/main/src/addins/WindowsPlatform/WindowsPlatform/Win32.cs +++ b/main/src/addins/WindowsPlatform/WindowsPlatform/Win32.cs @@ -24,100 +24,16 @@ using System.Runtime.InteropServices; namespace CustomControls.OS
{
- [Author("Franco, Gustavo")]
public static class Win32
{
- public const uint SHGFI_ICON = 0x100;
- public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
- public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
- public const uint SHGFI_ICONLOCATION = 0x1000;
- public const uint SHGFI_TYPENAME = 0x400;
- public const uint SHGFI_USEFILEATTRIBUTES = 0x10;
- public const uint FILE_ATTRIBUTES_NORMAL = 0x80;
internal const string USER32 = "user32.dll";
internal const string SHELL32 = "shell32.dll";
- internal const string SHLWAPI = "Shlwapi.dll";
+ internal const string SHLWAPI = "Shlwapi.dll";
- #region Delegates
- public delegate bool EnumWindowsCallBack(IntPtr hWnd, int lParam);
- #endregion
-
- #region USER32
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern IntPtr GetParent(IntPtr hWnd);
- [DllImport(Win32.USER32)]
- public static extern int GetDlgCtrlID(IntPtr hWndCtl);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto, ExactSpelling = true)]
- public static extern int MapWindowPoints(IntPtr hWnd, IntPtr hWndTo, ref POINT pt, int cPoints);
- [DllImport(Win32.USER32, SetLastError = true)]
- public static extern bool GetWindowInfo(IntPtr hwnd, out WINDOWINFO pwi);
- [DllImport(Win32.USER32)]
- public static extern void GetWindowText(IntPtr hWnd, StringBuilder param, int length);
- [DllImport(Win32.USER32)]
- public static extern void GetClassName(IntPtr hWnd, StringBuilder param, int length);
- [DllImport(Win32.USER32)]
- public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsCallBack lpEnumFunc, int lParam);
- [DllImport(Win32.USER32)]
- public static extern bool EnumWindows(EnumWindowsCallBack lpEnumFunc, int lParam);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern bool ReleaseCapture();
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern IntPtr SetCapture(IntPtr hWnd);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern IntPtr ChildWindowFromPointEx(IntPtr hParent, POINT pt, ChildFromPointFlags flags);
- [DllImport(Win32.USER32, EntryPoint = "FindWindowExA", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
- public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
- [DllImport(Win32.USER32)]
- public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern int PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern int PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern int SendMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, StringBuilder param);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, char[] chars);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern IntPtr BeginDeferWindowPos(int nNumWindows);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern IntPtr DeferWindowPos(IntPtr hWinPosInfo, IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int Width, int Height, SetWindowPosFlags flags);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern bool EndDeferWindowPos(IntPtr hWinPosInfo);
- [DllImport(Win32.USER32, CharSet = CharSet.Auto)]
- public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int Width, int Height, SetWindowPosFlags flags);
- [DllImport(Win32.USER32)]
- public static extern bool GetWindowRect(IntPtr hwnd, ref RECT rect);
- [DllImport(Win32.USER32)]
- public static extern bool GetClientRect(IntPtr hwnd, ref RECT rect);
- [DllImport(Win32.USER32)]
- public static extern bool DestroyIcon([In] IntPtr hIcon);
- [DllImport(Win32.SHELL32, CharSet = CharSet.Unicode)]
- public static extern IntPtr SHGetFileInfoW([In] string pszPath, uint dwFileAttributes, [In, Out] ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
- #endregion
-
- [DllImport (Win32.SHLWAPI, SetLastError = true, CharSet = CharSet.Unicode)]
- public static extern int AssocQueryStringW (AssociationFlags flags, AssociationString str, string assoc, string extra, StringBuilder outBuffer, ref int outBufferSize);
+ [DllImport (Win32.SHLWAPI, SetLastError = true, CharSet = CharSet.Unicode)]
+ public static extern int AssocQueryStringW (AssociationFlags flags, AssociationString str, string assoc, string extra, StringBuilder outBuffer, ref int outBufferSize);
}
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Enum |
- AttributeTargets.Interface |
- AttributeTargets.Struct,
- AllowMultiple = true)]
- [Author("Franco, Gustavo")]
- internal class AuthorAttribute : Attribute
- {
- #region Constructors
- public AuthorAttribute(string authorName)
- {
- }
- #endregion
- }
-
[Flags]
public enum AssociationFlags {
None = 0x00000000,
diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.cs b/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.cs index 4392189f51..9b6258af8a 100644 --- a/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.cs +++ b/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.cs @@ -87,7 +87,7 @@ namespace MonoDevelop.Platform return type ?? base.OnGetMimeTypeForUri (uri); } finally { - typeKey.Close (); + typeKey.Dispose (); } } @@ -103,10 +103,11 @@ namespace MonoDevelop.Platform public Gdk.Pixbuf CreateFromResource (Bitmap bitmap) { - MemoryStream ms = new MemoryStream (); - bitmap.Save (ms, ImageFormat.Png); - ms.Position = 0; - return new Gdk.Pixbuf (ms); + using (var ms = new MemoryStream ()) { + bitmap.Save (ms, ImageFormat.Png); + ms.Position = 0; + return new Gdk.Pixbuf (ms); + } } // Note: we can't reuse RectangleF because the layout is different... @@ -208,7 +209,7 @@ namespace MonoDevelop.Platform return psi; } - public override IProcessAsyncOperation StartConsoleProcess ( + public override ProcessAsyncOperation StartConsoleProcess ( string command, string arguments, string workingDirectory, IDictionary<string, string> environmentVariables, string title, bool pauseWhenFinished) diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.csproj b/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.csproj index 7a34098deb..c23f972d7b 100644 --- a/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.csproj +++ b/main/src/addins/WindowsPlatform/WindowsPlatform/WindowsPlatform.csproj @@ -87,9 +87,7 @@ <Compile Include="Dialogs\SelectFileDialogHandler.cs" /> <Compile Include="Dialogs\OpenFileDialogHandler.cs" /> <Compile Include="AssemblyInfo.cs" /> - <Compile Include="Enums.cs" /> <Compile Include="GdkWin32.cs" /> - <Compile Include="structs.cs" /> <Compile Include="Win32.cs" /> <Compile Include="WindowsPlatform.cs" /> <Compile Include="RecentFiles.cs" /> diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform/structs.cs b/main/src/addins/WindowsPlatform/WindowsPlatform/structs.cs deleted file mode 100644 index b39f00b566..0000000000 --- a/main/src/addins/WindowsPlatform/WindowsPlatform/structs.cs +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) 2006, Gustavo Franco
-// Email: gustavo_franco@hotmail.com
-// All rights reserved.
-
-// Redistribution and use in source and binary forms, with or without modification,
-// are permitted provided that the following conditions are met:
-
-// Redistributions of source code must retain the above copyright notice,
-// this list of conditions and the following disclaimer.
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following disclaimer in the documentation
-// and/or other materials provided with the distribution.
-
-// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
-// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
-// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
-// REMAINS UNCHANGED.
-
-using System;
-using System.Text;
-using System.Drawing;
-using System.Collections.Generic;
-using System.Runtime.InteropServices;
-
-namespace CustomControls.OS
-{
- #region WINDOWINFO
- [Author("Franco, Gustavo")]
- [StructLayout(LayoutKind.Sequential)]
- public struct WINDOWINFO
- {
- public UInt32 cbSize;
- public RECT rcWindow;
- public RECT rcClient;
- public UInt32 dwStyle;
- public UInt32 dwExStyle;
- public UInt32 dwWindowStatus;
- public UInt32 cxWindowBorders;
- public UInt32 cyWindowBorders;
- public UInt16 atomWindowType;
- public UInt16 wCreatorVersion;
- }
- #endregion
-
- #region POINT
- [Author("Franco, Gustavo")]
- [StructLayout(LayoutKind.Sequential)]
- public struct POINT
- {
- public int x;
- public int y;
-
- #region Constructors
- public POINT(int x, int y)
- {
- this.x = x;
- this.y = y;
- }
-
- public POINT(Point point)
- {
- x = point.X;
- y = point.Y;
- }
- #endregion
- }
- #endregion
-
- #region RECT
- [Author("Franco, Gustavo")]
- [StructLayout(LayoutKind.Sequential)]
- public struct RECT
- {
- public uint left;
- public uint top;
- public uint right;
- public uint bottom;
-
- #region Properties
- public POINT Location
- {
- get {return new POINT((int) left, (int) top);}
- set
- {
- right -= (left - (uint) value.x);
- bottom -= (bottom - (uint) value.y);
- left = (uint) value.x;
- top = (uint) value.y;
- }
- }
-
- public uint Width
- {
- get {return right - left;}
- set {right = left + value;}
- }
-
- public uint Height
- {
- get {return bottom - top;}
- set {bottom = top + value;}
- }
- #endregion
-
- #region Overrides
- public override string ToString()
- {
- return left + ":" + top + ":" + right + ":" + bottom;
- }
- #endregion
- }
- #endregion
-
- #region WINDOWPOS
- [Author("Franco, Gustavo")]
- [StructLayout(LayoutKind.Sequential)]
- public struct WINDOWPOS
- {
- public IntPtr hwnd;
- public IntPtr hwndAfter;
- public int x;
- public int y;
- public int cx;
- public int cy;
- public uint flags;
-
- #region Overrides
- public override string ToString()
- {
- return x + ":" + y + ":" + cx + ":" + cy + ":" + ((SWP_Flags) flags).ToString();
- }
- #endregion
- }
- #endregion
-
- #region NCCALCSIZE_PARAMS
- public struct NCCALCSIZE_PARAMS
- {
- public RECT rgrc1;
- public RECT rgrc2;
- public RECT rgrc3;
- public IntPtr lppos;
- }
- #endregion
-
- #region
- public struct NMHDR
- {
- public IntPtr hwndFrom;
- public IntPtr idFrom;
- public uint code;
- }
- #endregion
-
- #region OFNOTIFY
- [Author("Franco, Gustavo")]
- [StructLayout(LayoutKind.Sequential)]
- public struct OFNOTIFY
- {
- public NMHDR hdr;
- public IntPtr OPENFILENAME;
- public IntPtr fileNameShareViolation;
- }
- #endregion
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- public struct SHFILEINFO
- {
- public IntPtr hIcon;
- public int iIcon;
- public uint dwAttributes;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
- public string szDisplayName;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
- public string szTypeName;
- };
-}
diff --git a/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs b/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs index 4a1f05cd07..f0395d0aea 100644 --- a/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs +++ b/main/src/addins/Xml/Editor/BaseXmlEditorExtension.cs @@ -61,7 +61,7 @@ namespace MonoDevelop.Xml.Editor MonoDevelop.Ide.Gui.Components.PadTreeView outlineTreeView; TreeStore outlineTreeStore; - List<DotNetProject> ownerProjects; + List<DotNetProject> ownerProjects = new List<DotNetProject> (); #region Setup and teardown @@ -80,7 +80,12 @@ namespace MonoDevelop.Xml.Editor { base.Initialize (); - UpdateOwnerProjects (); + // Delay the execution of UpdateOwnerProjects since it may end calling Document.AttachToProject, + // which shouldn't be called while the extension chain is being initialized. + // TODO: Move handling of owner projects to Document + Application.Invoke (delegate { + UpdateOwnerProjects (); + }); var parser = new XmlParser (CreateRootState (), false); tracker = new DocumentStateTracker<XmlParser> (parser, Editor); @@ -110,7 +115,7 @@ namespace MonoDevelop.Xml.Editor ownerProjects = new List<DotNetProject> (); return; } - var projects = new HashSet<DotNetProject> (IdeApp.Workspace.GetAllSolutionItems<DotNetProject> ().Where (p => p.IsFileInProject (Document.FileName))); + var projects = new HashSet<DotNetProject> (IdeApp.Workspace.GetAllItems<DotNetProject> ().Where (p => p.IsFileInProject (Document.FileName))); if (ownerProjects == null || !projects.SetEquals (ownerProjects)) { ownerProjects = projects.OrderBy (p => p.Name).ToList (); var dnp = Document.Project as DotNetProject; @@ -827,8 +832,11 @@ namespace MonoDevelop.Xml.Editor void UpdatePath () { - List<XObject> l = GetCurrentPath (); + //update timeout could get called after disposed + if (tracker == null) + return; + List<XObject> l = GetCurrentPath (); //build the list var path = new List<PathEntry> (); diff --git a/main/src/addins/Xml/Editor/XmlEditorService.cs b/main/src/addins/Xml/Editor/XmlEditorService.cs index 513b2e7458..c5b0f82730 100644 --- a/main/src/addins/Xml/Editor/XmlEditorService.cs +++ b/main/src/addins/Xml/Editor/XmlEditorService.cs @@ -57,7 +57,7 @@ namespace MonoDevelop.Xml.Editor error.IsWarning = false; //Task task = new Task(fileName, message, column, line); - Task task = new Task (error); + UserTask task = new UserTask (error); TaskService.Errors.Add(task);
}
#endregion
@@ -100,7 +100,7 @@ namespace MonoDevelop.Xml.Editor } }*/ - public static IProgressMonitor GetMonitor () + public static ProgressMonitor GetMonitor () { return IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor ("XML", "md-xml-file-icon", true, true); }
@@ -198,7 +198,7 @@ namespace MonoDevelop.Xml.Editor /// <summary>
/// Checks that the xml in this view is well-formed.
/// </summary>
- public static XmlDocument ValidateWellFormedness (IProgressMonitor monitor, string xml, string fileName) + public static XmlDocument ValidateWellFormedness (ProgressMonitor monitor, string xml, string fileName) {
monitor.BeginTask (GettextCatalog.GetString ("Validating XML..."), 1); bool error = false;
@@ -227,7 +227,7 @@ namespace MonoDevelop.Xml.Editor /// <summary>
/// Validates the xml against known schemas.
/// </summary> - public static XmlDocument ValidateXml (IProgressMonitor monitor, string xml, string fileName) + public static XmlDocument ValidateXml (ProgressMonitor monitor, string xml, string fileName) { monitor.BeginTask (GettextCatalog.GetString ("Validating XML..."), 1); bool error = false;
@@ -293,7 +293,7 @@ namespace MonoDevelop.Xml.Editor /// <summary>
/// Validates the schema.
/// </summary> - public static XmlSchema ValidateSchema (IProgressMonitor monitor, string xml, string fileName) + public static XmlSchema ValidateSchema (ProgressMonitor monitor, string xml, string fileName) { monitor.BeginTask (GettextCatalog.GetString ("Validating schema..."), 1); bool error = false;
@@ -341,7 +341,7 @@ namespace MonoDevelop.Xml.Editor return error? null: schema;
}
- public static XslCompiledTransform ValidateStylesheet (IProgressMonitor monitor, string xml, string fileName)
+ public static XslCompiledTransform ValidateStylesheet (ProgressMonitor monitor, string xml, string fileName)
{
monitor.BeginTask (GettextCatalog.GetString ("Validating stylesheet..."), 1); bool error = true;
diff --git a/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs b/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs index a9dcf1d6b3..36685f8fa2 100644 --- a/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs +++ b/main/src/addins/Xml/Editor/XmlTextEditorExtension.cs @@ -503,7 +503,7 @@ namespace MonoDevelop.Xml.Editor try {
TaskService.Errors.Clear ();
string xml = Editor.Text; - using (IProgressMonitor monitor = XmlEditorService.GetMonitor ()) { + using (ProgressMonitor monitor = XmlEditorService.GetMonitor ()) { XmlDocument doc = XmlEditorService.ValidateWellFormedness (monitor, xml, FileName); if (doc == null) return; @@ -570,7 +570,7 @@ namespace MonoDevelop.Xml.Editor public void ValidateCommand () { TaskService.Errors.Clear (); - using (IProgressMonitor monitor = XmlEditorService.GetMonitor()) { + using (ProgressMonitor monitor = XmlEditorService.GetMonitor()) { if (IsSchema) XmlEditorService.ValidateSchema (monitor, Editor.Text, FileName); else
@@ -596,7 +596,7 @@ namespace MonoDevelop.Xml.Editor return; } - using (IProgressMonitor monitor = XmlEditorService.GetMonitor()) { + using (ProgressMonitor monitor = XmlEditorService.GetMonitor()) { try { string xsltContent; try { |