diff options
Diffstat (limited to 'main/src/core/MonoDevelop.Core/MonoDevelop.Projects')
69 files changed, 6341 insertions, 3680 deletions
diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildEventHandler.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildEventHandler.cs index ef76135af7..596d7ee072 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildEventHandler.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildEventHandler.cs @@ -35,10 +35,10 @@ namespace MonoDevelop.Projects public class BuildEventArgs: EventArgs { - IProgressMonitor monitor; + ProgressMonitor monitor; bool success; - public BuildEventArgs (IProgressMonitor monitor, bool success) + public BuildEventArgs (ProgressMonitor monitor, bool success) { this.monitor = monitor; this.success = success; @@ -48,7 +48,7 @@ namespace MonoDevelop.Projects this.FailedBuildCount = -1; } - public IProgressMonitor ProgressMonitor { + public ProgressMonitor ProgressMonitor { get { return monitor; } } @@ -72,7 +72,7 @@ namespace MonoDevelop.Projects get; set; } - public SolutionItem SolutionItem { + public SolutionFolderItem SolutionItem { get; set; } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildResult.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildResult.cs index 543ec390c1..9bfa798cba 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildResult.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildResult.cs @@ -43,6 +43,7 @@ namespace MonoDevelop.Projects string compilerOutput; List<BuildError> errors = new List<BuildError> (); IBuildTarget sourceTarget; + static BuildResult success = new BuildResult (); public BuildResult() { @@ -65,6 +66,18 @@ namespace MonoDevelop.Projects } } } + + public bool HasErrors { + get { return ErrorCount > 0; } + } + + public bool HasWarnings { + get { return WarningCount > 0; } + } + + public static BuildResult Success { + get { return success; } + } public ReadOnlyCollection<BuildError> Errors { get { return errors.AsReadOnly (); } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildTool.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildTool.cs index 43b3b5cfd6..46479efbc9 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildTool.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/BuildTool.cs @@ -34,6 +34,7 @@ using Mono.Addins; using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Core; using MonoDevelop.Core.Assemblies; +using System.Threading.Tasks; namespace MonoDevelop.Projects { @@ -48,6 +49,13 @@ namespace MonoDevelop.Projects public int Run (string[] arguments) { + var t = RunAsync (arguments); + t.Wait (); + return t.Result; + } + + public async Task<int> RunAsync (string[] arguments) + { Console.WriteLine (BrandingService.BrandApplicationName ("MonoDevelop Build Tool")); foreach (string s in arguments) ReadArgument (s); @@ -93,7 +101,7 @@ namespace MonoDevelop.Projects } } - IProgressMonitor monitor = new ConsoleProjectLoadProgressMonitor (new ConsoleProgressMonitor ()); + ProgressMonitor monitor = new ConsoleProjectLoadProgressMonitor (new ConsoleProgressMonitor ()); TargetRuntime targetRuntime = null; TargetRuntime defaultRuntime = Runtime.SystemAssemblyService.DefaultRuntime; @@ -106,11 +114,16 @@ namespace MonoDevelop.Projects IBuildTarget item; if (solFile != null) - item = Services.ProjectService.ReadWorkspaceItem (monitor, solFile); + item = await Services.ProjectService.ReadWorkspaceItem (monitor, solFile) as IBuildTarget; else - item = Services.ProjectService.ReadSolutionItem (monitor, itemFile); + item = await Services.ProjectService.ReadSolutionItem (monitor, itemFile); - using (var readItem = item) { + if (item == null) { + Console.WriteLine ("The file '" + file + "' can't be built"); + return 1; + } + + using (var readItem = (WorkspaceObject)item) { if (project != null) { Solution solution = item as Solution; item = null; @@ -130,21 +143,25 @@ namespace MonoDevelop.Projects monitor = new ConsoleProgressMonitor (); BuildResult res = null; - if (item is SolutionEntityItem && ((SolutionEntityItem)item).ParentSolution == null) { + if (item is SolutionItem && ((SolutionItem)item).ParentSolution == null) { ConfigurationSelector configuration = new ItemConfigurationSelector (config); - res = item.RunTarget (monitor, command, configuration); + if (command == ProjectService.BuildTarget) + res = await item.Build (monitor, configuration); + else if (command == ProjectService.CleanTarget) + res = await item.Clean (monitor, configuration); } else { ConfigurationSelector configuration = new SolutionConfigurationSelector (config); - SolutionEntityItem solutionEntityItem = item as SolutionEntityItem; + SolutionItem solutionEntityItem = item as SolutionItem; if (solutionEntityItem != null) { if (command == ProjectService.BuildTarget) - res = solutionEntityItem.Build (monitor, configuration, true); + res = await solutionEntityItem.Build (monitor, configuration, true); else if (command == ProjectService.CleanTarget) - solutionEntityItem.Clean (monitor, configuration); - else - res = item.RunTarget (monitor, command, configuration); + await solutionEntityItem.Clean (monitor, configuration); + else if (solutionEntityItem is Project) + res = await ((Project)item).RunTarget (monitor, command, configuration); } else { - res = item.RunTarget (monitor, command, configuration); + Console.WriteLine ("The project '" + project + "' can't be built"); + return 1; } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ChainedExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ChainedExtension.cs new file mode 100644 index 0000000000..48af259aba --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ChainedExtension.cs @@ -0,0 +1,94 @@ +// +// ChainedExtension.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 System.Reflection; +using System.Linq; +using System.Collections.Generic; + +namespace MonoDevelop.Projects +{ + public class ChainedExtension: IDisposable + { + ChainedExtension nextInChain; + + internal protected static T FindNextImplementation<T> (ChainedExtension next) where T:class + { + if (next == null) + return null; + + var nextT = next as T; + if (nextT == null) + return FindNextImplementation<T> (next.nextInChain); + + foreach (var m in typeof(T).GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { + MethodInfo method = m as MethodInfo; + if (method == null) { + var prop = m as PropertyInfo; + if (prop != null) { + method = prop.GetGetMethod (); + if (method == null) + method = prop.GetSetMethod (); + } + } + if (method != null && method.IsVirtual && method.Name != "InitializeChain") { + var tm = next.GetType ().GetMethod (method.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, method.GetParameters ().Select (p=>p.ParameterType).ToArray (), null); + if (tm == null) + continue; + if (tm.DeclaringType != typeof(T)) + return nextT; + } + } + + return FindNextImplementation<T> (next.nextInChain); + } + + internal void Init (ChainedExtension next) + { + nextInChain = next; + InitializeChain (next); + } + + internal protected virtual void InitializeChain (ChainedExtension next) + { + } + + internal ChainedExtension Next { + get { return nextInChain; } + } + + internal void DisposeChain () + { + Dispose (); + if (nextInChain != null) + nextInChain.DisposeChain (); + } + + public virtual void Dispose () + { + } + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CleanEventHandler.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CleanEventHandler.cs index 5d0dc54264..430a43b3fe 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CleanEventHandler.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CleanEventHandler.cs @@ -33,14 +33,14 @@ namespace MonoDevelop.Projects public class CleanEventArgs : EventArgs { - IProgressMonitor monitor; + ProgressMonitor monitor; - public CleanEventArgs (IProgressMonitor monitor) + public CleanEventArgs (ProgressMonitor monitor) { this.monitor = monitor; } - public IProgressMonitor Monitor { + public ProgressMonitor Monitor { get { return monitor; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CombineEntryRenamedEventArgs.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CombineEntryRenamedEventArgs.cs index 41f95e07ad..c7efbcef93 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CombineEntryRenamedEventArgs.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CombineEntryRenamedEventArgs.cs @@ -37,7 +37,7 @@ namespace MonoDevelop.Projects string oldName; string newName; - public SolutionItemRenamedEventArgs (SolutionItem node, string oldName, string newName) + public SolutionItemRenamedEventArgs (SolutionFolderItem node, string oldName, string newName) : base (node) { this.oldName = oldName; diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CompiledAssemblyProject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CompiledAssemblyProject.cs index 481bcd9ecf..bbaa65182f 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CompiledAssemblyProject.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CompiledAssemblyProject.cs @@ -34,6 +34,9 @@ using MonoDevelop.Core.ProgressMonitoring; using System.Collections.Generic; using Mono.Cecil.Mdb; using Mono.Cecil.Cil; +using System.Threading.Tasks; +using MonoDevelop.Core.Serialization; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { @@ -46,9 +49,9 @@ namespace MonoDevelop.Projects AddNewConfiguration ("Default"); } - public override IEnumerable<string> GetProjectTypes () + protected override void OnGetProjectTypes (HashSet<string> types) { - yield return "CompiledAssembly"; + types.Add ("CompiledAssembly"); } public override IconId StockIcon { @@ -137,17 +140,12 @@ namespace MonoDevelop.Projects return string.Join (Path.DirectorySeparatorChar.ToString (), s1, 0, n); } - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { - return new BuildResult (); + return Task.FromResult (BuildResult.Success); } - internal protected override bool OnGetNeedsBuilding (ConfigurationSelector configuration) - { - return false; - } - - internal protected override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + protected async override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { ProjectConfiguration conf = (ProjectConfiguration) GetConfiguration (configuration); monitor.Log.WriteLine (GettextCatalog.GetString ("Running {0} ...", FileName)); @@ -156,8 +154,6 @@ namespace MonoDevelop.Projects ? context.ExternalConsoleFactory.CreateConsole (!conf.PauseConsoleOutput) : context.ConsoleFactory.CreateConsole (!conf.PauseConsoleOutput); - AggregatedOperationMonitor aggregatedOperationMonitor = new AggregatedOperationMonitor (monitor); - try { try { ExecutionCommand executionCommand = CreateExecutionCommand (configuration, conf); @@ -167,14 +163,16 @@ namespace MonoDevelop.Projects return; } - IProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute (executionCommand, console); - aggregatedOperationMonitor.AddOperation (asyncOp); - asyncOp.WaitForCompleted (); + ProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute (executionCommand, console); + var stopper = monitor.CancellationToken.Register (asyncOp.Cancel); + + await asyncOp.Task; + + stopper.Dispose (); monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", asyncOp.ExitCode)); } finally { console.Dispose (); - aggregatedOperationMonitor.Dispose (); } } catch (Exception ex) { LoggingService.LogError (string.Format ("Cannot execute \"{0}\"", FileName), ex); @@ -182,7 +180,7 @@ namespace MonoDevelop.Projects } } - internal protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) + protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) { ProjectConfiguration config = (ProjectConfiguration) GetConfiguration (configuration); if (config == null) @@ -201,6 +199,32 @@ namespace MonoDevelop.Projects cmd.EnvironmentVariables = new Dictionary<string, string> (configuration.EnvironmentVariables); return cmd; } + + public override bool HasSlnData { + get { + return true; + } + } + + public override DataItem WriteSlnData () + { + DataSerializer ser = new DataSerializer (MSBuildProjectService.DataContext); + ser.SerializationContext.BaseFile = FileName; + ser.SerializationContext.DirectorySeparatorChar = '\\'; + DataItem data = (DataItem) ser.Serialize (this, typeof(CompiledAssemblyProject)); + return data; + } + + public override void ReadSlnData (DataItem item) + { + // Remove the default configuration, since new ones will be loaded + Configurations.Clear (); + + DataSerializer ser = new DataSerializer (MSBuildProjectService.DataContext); + ser.SerializationContext.BaseFile = FileName; + ser.SerializationContext.DirectorySeparatorChar = '\\'; + ser.Deserialize (this, item); + } } public class CompiledAssemblyExtension: ProjectServiceExtension @@ -212,22 +236,17 @@ namespace MonoDevelop.Projects return base.IsSolutionItemFile (fileName); } - protected override SolutionEntityItem LoadSolutionItem (IProgressMonitor monitor, string fileName) + protected override Task<SolutionItem> LoadSolutionItem (ProgressMonitor monitor, string fileName) { if (fileName.ToLower().EndsWith (".exe") || fileName.ToLower().EndsWith (".dll")) { - CompiledAssemblyProject p = new CompiledAssemblyProject (); - p.LoadFrom (fileName); - return p; + return Task<SolutionItem>.Factory.StartNew (delegate { + CompiledAssemblyProject p = new CompiledAssemblyProject (); + p.LoadFrom (fileName); + return p; + }); } return base.LoadSolutionItem (monitor, fileName); } - - public override void Save (IProgressMonitor monitor, SolutionEntityItem item) - { -// if (item is CompiledAssemblyProject) -// return; - base.Save (monitor, item); - } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ConfigurationEventHandler.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ConfigurationEventHandler.cs index fdec84f720..61d537dd5f 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ConfigurationEventHandler.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ConfigurationEventHandler.cs @@ -38,7 +38,7 @@ namespace MonoDevelop.Projects { ItemConfiguration configuration; - public ConfigurationEventArgs (SolutionEntityItem entry, ItemConfiguration configuration): base (entry) + public ConfigurationEventArgs (SolutionItem entry, ItemConfiguration configuration): base (entry) { this.configuration = configuration; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommand.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommand.cs index 115edb369f..f74b6f51e8 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommand.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommand.cs @@ -35,6 +35,8 @@ using MonoDevelop.Core.Execution; using MonoDevelop.Core.StringParsing; using System.Collections.Generic; using MonoDevelop.Core.ProgressMonitoring; +using System.Threading.Tasks; +using System.Threading; namespace MonoDevelop.Projects { @@ -98,7 +100,7 @@ namespace MonoDevelop.Projects set { pauseExternalConsole = value; } } - public string GetCommandFile (IWorkspaceObject entry, ConfigurationSelector configuration) + public string GetCommandFile (WorkspaceObject entry, ConfigurationSelector configuration) { string exe, args; StringTagModel tagSource = GetTagModel (entry, configuration); @@ -106,7 +108,7 @@ namespace MonoDevelop.Projects return exe; } - public string GetCommandArgs (IWorkspaceObject entry, ConfigurationSelector configuration) + public string GetCommandArgs (WorkspaceObject entry, ConfigurationSelector configuration) { string exe, args; StringTagModel tagSource = GetTagModel (entry, configuration); @@ -114,7 +116,7 @@ namespace MonoDevelop.Projects return args; } - public FilePath GetCommandWorkingDir (IWorkspaceObject entry, ConfigurationSelector configuration) + public FilePath GetCommandWorkingDir (WorkspaceObject entry, ConfigurationSelector configuration) { StringTagModel tagSource = GetTagModel (entry, configuration); if (string.IsNullOrEmpty (workingdir)) @@ -135,10 +137,10 @@ namespace MonoDevelop.Projects return cmd; } - StringTagModel GetTagModel (IWorkspaceObject entry, ConfigurationSelector configuration) + StringTagModel GetTagModel (WorkspaceObject entry, ConfigurationSelector configuration) { - if (entry is SolutionItem) - return ((SolutionItem)entry).GetStringTagModel (configuration); + if (entry is SolutionFolderItem) + return ((SolutionFolderItem)entry).GetStringTagModel (configuration); else if (entry is WorkspaceItem) return ((WorkspaceItem)entry).GetStringTagModel (); else @@ -172,7 +174,7 @@ namespace MonoDevelop.Projects args = StringParserService.Parse (args, tagSource); } - public ProcessExecutionCommand CreateExecutionCommand (IWorkspaceObject entry, ConfigurationSelector configuration) + public ProcessExecutionCommand CreateExecutionCommand (WorkspaceObject entry, ConfigurationSelector configuration) { string exe, args; StringTagModel tagSource = GetTagModel (entry, configuration); @@ -207,12 +209,12 @@ namespace MonoDevelop.Projects return cmd; } - public void Execute (IProgressMonitor monitor, IWorkspaceObject entry, ConfigurationSelector configuration) + public Task<bool> Execute (ProgressMonitor monitor, WorkspaceObject entry, ConfigurationSelector configuration) { - Execute (monitor, entry, null, configuration); + return Execute (monitor, entry, null, configuration); } - public bool CanExecute (IWorkspaceObject entry, ExecutionContext context, ConfigurationSelector configuration) + public bool CanExecute (WorkspaceObject entry, ExecutionContext context, ConfigurationSelector configuration) { if (string.IsNullOrEmpty (command)) return false; @@ -224,7 +226,7 @@ namespace MonoDevelop.Projects return context.ExecutionHandler.CanExecute (cmd); } - public void Execute (IProgressMonitor monitor, IWorkspaceObject entry, ExecutionContext context, + public async Task<bool> Execute (ProgressMonitor monitor, WorkspaceObject entry, ExecutionContext context, ConfigurationSelector configuration) { ProcessExecutionCommand cmd = CreateExecutionCommand (entry, configuration); @@ -233,12 +235,12 @@ namespace MonoDevelop.Projects if (!Directory.Exists (cmd.WorkingDirectory)) { monitor.ReportError (GettextCatalog.GetString ("Custom command working directory does not exist"), null); - return; + return false; } - AggregatedOperationMonitor aggMon = null; - IProcessAsyncOperation oper = null; + ProcessAsyncOperation oper = null; IConsole console = null; + var result = true; try { if (context != null) { @@ -254,35 +256,33 @@ namespace MonoDevelop.Projects cmd.WorkingDirectory, console, null); } else { oper = Runtime.ProcessService.StartProcess (cmd.Command, cmd.Arguments, - cmd.WorkingDirectory, monitor.Log, monitor.Log, null, false); + cmd.WorkingDirectory, monitor.Log, monitor.Log, null, false).ProcessAsyncOperation; } } - aggMon = new AggregatedOperationMonitor (monitor, oper); - oper.WaitForCompleted (); - if (!oper.Success) { + + var stopper = monitor.CancellationToken.Register (oper.Cancel); + + await oper.Task; + + stopper.Dispose (); + + if (oper.ExitCode != 0) { monitor.ReportError ("Custom command failed (exit code: " + oper.ExitCode + ")", null); } } catch (Win32Exception w32ex) { monitor.ReportError (GettextCatalog.GetString ("Failed to execute custom command '{0}': {1}", cmd.Command, w32ex.Message), null); - return; + return false; } catch (Exception ex) { LoggingService.LogError ("Command execution failed", ex); throw new UserException (GettextCatalog.GetString ("Command execution failed: {0}", ex.Message)); } finally { - if (oper == null || !oper.Success) { - monitor.AsyncOperation.Cancel (); - } - if (oper != null) { - oper.Dispose (); - } + result = oper != null && oper.ExitCode == 0; if (console != null) { console.Dispose (); } - if (aggMon != null) { - aggMon.Dispose (); - } } + return result; } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommandCollection.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommandCollection.cs index 797ee6da64..ee37994054 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommandCollection.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommandCollection.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; using MonoDevelop.Core; +using System.Threading.Tasks; namespace MonoDevelop.Projects { @@ -48,19 +49,20 @@ namespace MonoDevelop.Projects Add (cmd.Clone ()); } - public void ExecuteCommand (IProgressMonitor monitor, IWorkspaceObject entry, CustomCommandType type, ConfigurationSelector configuration) + public Task<bool> ExecuteCommand (ProgressMonitor monitor, WorkspaceObject entry, CustomCommandType type, ConfigurationSelector configuration) { - ExecuteCommand (monitor, entry, type, null, configuration); + return ExecuteCommand (monitor, entry, type, null, configuration); } - public void ExecuteCommand (IProgressMonitor monitor, IWorkspaceObject entry, CustomCommandType type, ExecutionContext context, ConfigurationSelector configuration) + public async Task<bool> ExecuteCommand (ProgressMonitor monitor, WorkspaceObject entry, CustomCommandType type, ExecutionContext context, ConfigurationSelector configuration) { foreach (CustomCommand cmd in this) { - if (cmd.Type == type) - cmd.Execute (monitor, entry, context, configuration); - if (monitor.IsCancelRequested) - break; + if (cmd.Type == type) { + if (!await cmd.Execute (monitor, entry, context, configuration)) + return false; + } } + return true; } public bool HasCommands (CustomCommandType type) @@ -71,7 +73,7 @@ namespace MonoDevelop.Projects return false; } - public bool CanExecute (IWorkspaceObject entry, CustomCommandType type, ExecutionContext context, ConfigurationSelector configuration) + public bool CanExecute (WorkspaceObject entry, CustomCommandType type, ExecutionContext context, ConfigurationSelector configuration) { // Note: if this gets changed to return true if *any* of the commands can execute, then // ExecuteCommand() needs to be fixed to only execute commands that can be executed. diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommandExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommandExtension.cs deleted file mode 100644 index fc0a9bf77b..0000000000 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/CustomCommandExtension.cs +++ /dev/null @@ -1,101 +0,0 @@ -// CustomCommandExtension.cs -// -// Author: -// Lluis Sanchez Gual <lluis@novell.com> -// -// Copyright (c) 2007 Novell, Inc (http://www.novell.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 System.CodeDom.Compiler; -using MonoDevelop.Core.Execution; - -namespace MonoDevelop.Projects -{ - internal class CustomCommandExtension: ProjectServiceExtension - { - protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) - { - SolutionItemConfiguration conf = entry.GetConfiguration (configuration) as SolutionItemConfiguration; - if (conf != null) { - if (conf.CustomCommands.CanExecute (entry, CustomCommandType.BeforeBuild, null, configuration)) - conf.CustomCommands.ExecuteCommand (monitor, entry, CustomCommandType.BeforeBuild, configuration); - - if (monitor.IsCancelRequested) - return new BuildResult (new CompilerResults (null), ""); - } - - BuildResult res = base.Build (monitor, entry, configuration); - - if (conf != null && !monitor.IsCancelRequested && !res.Failed) { - if (conf.CustomCommands.CanExecute (entry, CustomCommandType.AfterBuild, null, configuration)) - conf.CustomCommands.ExecuteCommand (monitor, entry, CustomCommandType.AfterBuild, configuration); - } - - return res; - } - - protected override void Clean (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) - { - SolutionItemConfiguration conf = entry.GetConfiguration (configuration) as SolutionItemConfiguration; - if (conf != null) { - if (conf.CustomCommands.CanExecute (entry, CustomCommandType.BeforeClean, null, configuration)) - conf.CustomCommands.ExecuteCommand (monitor, entry, CustomCommandType.BeforeClean, configuration); - - if (monitor.IsCancelRequested) - return; - } - - base.Clean (monitor, entry, configuration); - - if (conf != null && !monitor.IsCancelRequested) { - if (conf.CustomCommands.CanExecute (entry, CustomCommandType.AfterClean, null, configuration)) - conf.CustomCommands.ExecuteCommand (monitor, entry, CustomCommandType.AfterClean, configuration); - } - } - - protected override void Execute (IProgressMonitor monitor, SolutionEntityItem entry, ExecutionContext context, ConfigurationSelector configuration) - { - SolutionItemConfiguration conf = entry.GetConfiguration (configuration) as SolutionItemConfiguration; - if (conf != null) { - ExecutionContext localContext = new ExecutionContext (Runtime.ProcessService.DefaultExecutionHandler, context.ConsoleFactory, context.ExecutionTarget); - - if (conf.CustomCommands.CanExecute (entry, CustomCommandType.BeforeExecute, localContext, configuration)) - conf.CustomCommands.ExecuteCommand (monitor, entry, CustomCommandType.BeforeExecute, localContext, configuration); - - if (monitor.IsCancelRequested) - return; - } - - base.Execute (monitor, entry, context, configuration); - - if (conf != null && !monitor.IsCancelRequested) { - ExecutionContext localContext = new ExecutionContext (Runtime.ProcessService.DefaultExecutionHandler, context.ConsoleFactory, context.ExecutionTarget); - - if (conf.CustomCommands.CanExecute (entry, CustomCommandType.AfterExecute, localContext, configuration)) - conf.CustomCommands.ExecuteCommand (monitor, entry, CustomCommandType.AfterExecute, localContext, configuration); - } - } - } -} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetAssemblyProject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetAssemblyProject.cs deleted file mode 100644 index cba01e80c1..0000000000 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetAssemblyProject.cs +++ /dev/null @@ -1,108 +0,0 @@ -// -// DotNetAssemblyProject.cs -// -// Author: -// Lluis Sanchez Gual <lluis@novell.com> -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.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.Xml; -using MonoDevelop.Core; -using MonoDevelop.Core.Assemblies; - -namespace MonoDevelop.Projects -{ - [ProjectModelDataItem ("DotNetProject")] - public class DotNetAssemblyProject: DotNetProject - { - public DotNetAssemblyProject () - { - } - - public DotNetAssemblyProject (string languageName) : base (languageName) - { - } - - public DotNetAssemblyProject (string languageName, ProjectCreateInformation projectCreateInfo, XmlElement projectOptions): - base (languageName, projectCreateInfo, projectOptions) - { - } - - public override System.Collections.Generic.IEnumerable<string> GetProjectTypes () - { - yield return "DotNetAssembly"; - foreach (var pt in base.GetProjectTypes ()) - yield return pt; - } - - public override bool SupportsFramework (TargetFramework framework) - { - // DotNetAssemblyProject can only generate assemblies for the regular framework. - // Special frameworks such as Moonlight or MonoTouch must subclass DotNetProject directly. - if (!framework.CanReferenceAssembliesTargetingFramework (TargetFrameworkMoniker.NET_1_1)) - return false; - - return base.SupportsFramework (framework); - } - - public override TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format) - { - switch (format.Id) { - case "MSBuild05": - return TargetFrameworkMoniker.NET_2_0; - case "MSBuild08": - return TargetFrameworkMoniker.NET_2_0; - case "MSBuild10": - case "MSBuild12": - return TargetFrameworkMoniker.NET_4_0; - } - return Services.ProjectService.DefaultTargetFramework.Id; - } - - protected override string GetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo) - { - if (CompileTarget == CompileTarget.Library) - return string.Empty; - - // Guess a good default platform for the project - if (projectCreateInfo.ParentFolder != null && projectCreateInfo.ParentFolder.ParentSolution != null) { - ItemConfiguration conf = projectCreateInfo.ParentFolder.ParentSolution.GetConfiguration (projectCreateInfo.ActiveConfiguration); - if (conf != null) - return conf.Platform; - else { - string curName, curPlatform, bestPlatform = null; - string sconf = projectCreateInfo.ActiveConfiguration.ToString (); - ItemConfiguration.ParseConfigurationId (sconf, out curName, out curPlatform); - foreach (ItemConfiguration ic in projectCreateInfo.ParentFolder.ParentSolution.Configurations) { - if (ic.Platform == curPlatform) - return curPlatform; - if (ic.Name == curName) - bestPlatform = ic.Platform; - } - if (bestPlatform != null) - return bestPlatform; - } - } - return Services.ProjectService.DefaultPlatformTarget; - } - } -} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ConfigurationParameters.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetCompilerParameters.cs index 9ff5f46356..c45f57b51c 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ConfigurationParameters.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetCompilerParameters.cs @@ -31,9 +31,7 @@ using System.Linq; namespace MonoDevelop.Projects { - ///<summary>This should really be called DotNetCompilerParameters</summary> - [DataItem (FallbackType=typeof(UnknownCompilationParameters))] - public abstract class ConfigurationParameters: ProjectParameters + public abstract class DotNetCompilerParameters: ProjectParameters { DotNetProjectConfiguration configuration; @@ -58,9 +56,9 @@ namespace MonoDevelop.Projects return GetDefineSymbols ().Any (s => s == symbol); } - public new ConfigurationParameters Clone () + public new DotNetCompilerParameters Clone () { - return (ConfigurationParameters) base.Clone (); + return (DotNetCompilerParameters) base.Clone (); } public DotNetProjectConfiguration ParentConfiguration { @@ -71,11 +69,7 @@ namespace MonoDevelop.Projects ParentProject = configuration.ParentItem; } } - } - public abstract class DotNetConfigurationParameters : ConfigurationParameters - { - public abstract bool NoStdLib { get; set; } + public virtual bool NoStdLib { get; set; } } - } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProject.cs index d6a7a8c7f0..e2148a39ac 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProject.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProject.cs @@ -2,7 +2,7 @@ // // Author: // Lluis Sanchez Gual <lluis@novell.com> -// +// // Copyright (c) 2009 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy @@ -44,53 +44,67 @@ using MonoDevelop.Projects.Extensions; using MonoDevelop.Projects.Formats.MSBuild; using MonoDevelop.Core.Assemblies; using System.Globalization; +using System.Threading.Tasks; +using Mono.Addins; namespace MonoDevelop.Projects { - [DataInclude(typeof(DotNetProjectConfiguration))] - [ProjectModelDataItem ("AbstractDotNetProject")] - public abstract class DotNetProject : Project, IAssemblyProject, IDotNetFileContainer + public class DotNetProject : Project, IAssemblyProject, IDotNetFileContainer { bool usePartialTypes = true; - ProjectParameters languageParameters; DirectoryAssemblyContext privateAssemblyContext; ComposedAssemblyContext composedAssemblyContext; IAssemblyContext currentRuntimeContext; - [ItemProperty("OutputType")] CompileTarget compileTarget; IDotNetLanguageBinding languageBinding; protected ProjectReferenceCollection projectReferences; - [ItemProperty("RootNamespace", DefaultValue = "")] protected string defaultNamespace = String.Empty; - - public DotNetProject () + + protected DotNetProject () { - Runtime.SystemAssemblyService.DefaultRuntimeChanged += RuntimeSystemAssemblyServiceDefaultRuntimeChanged; + Initialize (this); + } + + protected DotNetProject (string languageName, params string[] flavorIds): base (flavorIds) + { + this.languageName = languageName; + Initialize (this); + } + + protected override void OnInitialize () + { + UseMSBuildEngineByDefault = true; + RequireMSBuildEngine = false; projectReferences = new ProjectReferenceCollection (); Items.Bind (projectReferences); - if (IsLibraryBasedProjectType) - CompileTarget = CompileTarget.Library; FileService.FileRemoved += OnFileRemoved; + Runtime.SystemAssemblyService.DefaultRuntimeChanged += RuntimeSystemAssemblyServiceDefaultRuntimeChanged; + + base.OnInitialize (); + + if (languageName == null) + languageName = MSBuildProjectService.GetLanguageFromGuid (TypeGuid); } - public DotNetProject (string languageName) : this() + protected override void OnExtensionChainInitialized () { - // Language name must be set before the item handler is assigned - this.languageName = languageName; - this.languageBinding = FindLanguage (languageName); - - if (this.languageBinding != null) - this.StockIcon = this.languageBinding.ProjectStockIcon; + base.OnExtensionChainInitialized (); this.usePartialTypes = SupportsPartialTypes; + + if (LanguageBinding != null) + this.StockIcon = LanguageBinding.ProjectStockIcon; + + if (IsLibraryBasedProjectType) + CompileTarget = CompileTarget.Library; } - public DotNetProject (string languageName, ProjectCreateInformation projectCreateInfo, XmlElement projectOptions) : this(languageName) + public override void InitializeNew (ProjectCreateInformation projectCreateInfo, XmlElement projectOptions) { if ((projectOptions != null) && (projectOptions.Attributes ["Target"] != null)) CompileTarget = (CompileTarget)Enum.Parse (typeof(CompileTarget), projectOptions.Attributes ["Target"].Value); @@ -98,8 +112,7 @@ namespace MonoDevelop.Projects CompileTarget = CompileTarget.Library; if (this.LanguageBinding != null) { - LanguageParameters = languageBinding.CreateProjectParameters (projectOptions); - + bool externalConsole = false; string platform = null; @@ -117,22 +130,22 @@ namespace MonoDevelop.Projects } string platformSuffix = string.IsNullOrEmpty (platform) ? string.Empty : "|" + platform; DotNetProjectConfiguration configDebug = CreateConfiguration ("Debug" + platformSuffix) as DotNetProjectConfiguration; - configDebug.CompilationParameters = languageBinding.CreateCompilationParameters (projectOptions); + configDebug.CompilationParameters = LanguageBinding.CreateCompilationParameters (projectOptions); configDebug.DebugMode = true; configDebug.ExternalConsole = externalConsole; configDebug.PauseConsoleOutput = externalConsole; Configurations.Add (configDebug); DotNetProjectConfiguration configRelease = CreateConfiguration ("Release" + platformSuffix) as DotNetProjectConfiguration; - + if (projectOptions != null) { XmlElement releaseProjectOptions = (XmlElement)projectOptions.CloneNode (true); releaseProjectOptions.SetAttribute ("Release", "True"); - configRelease.CompilationParameters = languageBinding.CreateCompilationParameters (releaseProjectOptions); + configRelease.CompilationParameters = LanguageBinding.CreateCompilationParameters (releaseProjectOptions); } else { - configRelease.CompilationParameters = languageBinding.CreateCompilationParameters (null); + configRelease.CompilationParameters = LanguageBinding.CreateCompilationParameters (null); } - + configRelease.CompilationParameters.RemoveDefineSymbol ("DEBUG"); configRelease.DebugMode = false; configRelease.ExternalConsole = externalConsole; @@ -184,9 +197,32 @@ namespace MonoDevelop.Projects return Runtime.SystemAssemblyService.GetTargetFramework (moniker); } - public override IEnumerable<string> GetProjectTypes () + protected override void OnGetProjectTypes (HashSet<string> types) + { + types.Add ("DotNet"); + types.Add ("DotNetAssembly"); + } + + DotNetProjectExtension projectExtension; + DotNetProjectExtension ProjectExtension { + get { + if (projectExtension == null) + projectExtension = ExtensionChain.GetExtension<DotNetProjectExtension> (); + return projectExtension; + } + } + + protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions () + { + return base.CreateDefaultExtensions ().Concat (Enumerable.Repeat (new DefaultDotNetProjectExtension (), 1)); + } + + protected override ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item) { - yield return "DotNet"; + if (item.Name == "Reference" || item.Name == "ProjectReference") + return new ProjectReference (); + + return base.OnCreateProjectItem (item); } private string languageName; @@ -195,22 +231,53 @@ namespace MonoDevelop.Projects } public override string[] SupportedLanguages { - get { return new string[] {"",languageName}; } + get { return ProjectExtension.SupportedLanguages; } } public virtual bool IsLibraryBasedProjectType { - get { return false; } + get { return ProjectExtension.IsLibraryBasedProjectType; } + } + + public bool IsPortableLibrary { + get { return GetService<PortableDotNetProjectFlavor> () != null; } } public virtual bool GeneratesDebugInfoFile { - get { return true; } + get { return ProjectExtension.GeneratesDebugInfoFile; } } - - protected virtual string GetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo) + + protected string GetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo) { - return string.Empty; + return ProjectExtension.OnGetDefaultTargetPlatform (projectCreateInfo); } - + + protected virtual string OnGetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo) + { + if (CompileTarget == CompileTarget.Library) + return string.Empty; + + // Guess a good default platform for the project + if (projectCreateInfo.ParentFolder != null && projectCreateInfo.ParentFolder.ParentSolution != null) { + ItemConfiguration conf = projectCreateInfo.ParentFolder.ParentSolution.GetConfiguration (projectCreateInfo.ActiveConfiguration); + if (conf != null) + return conf.Platform; + else { + string curName, curPlatform, bestPlatform = null; + string sconf = projectCreateInfo.ActiveConfiguration.ToString (); + ItemConfiguration.ParseConfigurationId (sconf, out curName, out curPlatform); + foreach (ItemConfiguration ic in projectCreateInfo.ParentFolder.ParentSolution.Configurations) { + if (ic.Platform == curPlatform) + return curPlatform; + if (ic.Name == curName) + bestPlatform = ic.Platform; + } + if (bestPlatform != null) + return bestPlatform; + } + } + return Services.ProjectService.DefaultPlatformTarget; + } + public ProjectReferenceCollection References { get { return projectReferences; } } @@ -229,6 +296,10 @@ namespace MonoDevelop.Projects public virtual bool CanReferenceProject (DotNetProject targetProject, out string reason) { + return ProjectExtension.OnGetCanReferenceProject (targetProject, out reason); + } + bool CheckCanReferenceProject (DotNetProject targetProject, out string reason) + { if (!TargetFramework.CanReferenceAssembliesTargetingFramework (targetProject.TargetFramework)) { reason = GettextCatalog.GetString ("Incompatible target framework: {0}", targetProject.TargetFramework.Id); return false; @@ -264,20 +335,6 @@ namespace MonoDevelop.Projects } } - [ItemProperty("LanguageParameters")] - public ProjectParameters LanguageParameters { - get { - if (languageParameters == null && LanguageBinding != null) - LanguageParameters = LanguageBinding.CreateProjectParameters (null); - return languageParameters; - } - internal set { - languageParameters = value; - if (languageParameters != null) - languageParameters.ParentProject = this; - } - } - /// <summary> /// Default namespace setting. May be empty, use GetDefaultNamespace to get a usable value. /// </summary> @@ -288,7 +345,7 @@ namespace MonoDevelop.Projects NotifyModified ("DefaultNamespace"); } } - + /// <summary> /// Given a namespace, removes from it the implicit namespace of the project, /// if there is one. This depends on the target language. For example, in VB.NET @@ -296,7 +353,7 @@ namespace MonoDevelop.Projects /// </summary> public string StripImplicitNamespace (string ns) { - if ((LanguageParameters is DotNetProjectParameters) && ((DotNetProjectParameters)LanguageParameters).DefaultNamespaceIsImplicit) { + if (DefaultNamespaceIsImplicit) { if (DefaultNamespace.Length > 0 && ns.StartsWith (DefaultNamespace + ".")) return ns.Substring (DefaultNamespace.Length + 1); else if (DefaultNamespace == ns) @@ -305,23 +362,26 @@ namespace MonoDevelop.Projects return ns; } + public bool DefaultNamespaceIsImplicit { get; set; } + IResourceHandler resourceHandler; public IResourceHandler ResourceHandler { get { if (resourceHandler == null) { DotNetNamingPolicy pol = Policies.Get<DotNetNamingPolicy> (); - if (pol.ResourceNamePolicy == ResourceNamePolicy.FileFormatDefault) - resourceHandler = ItemHandler as IResourceHandler; - else if (pol.ResourceNamePolicy == ResourceNamePolicy.MSBuild) - resourceHandler = MSBuildProjectService.GetResourceHandlerForItem (this); - if (resourceHandler == null) + if (pol.ResourceNamePolicy == ResourceNamePolicy.FileFormatDefault || pol.ResourceNamePolicy == ResourceNamePolicy.MSBuild) { + resourceHandler = GetService<IResourceHandler> (); + if (resourceHandler == null) + resourceHandler = MSBuildResourceHandler.Instance; + } + else resourceHandler = DefaultResourceHandler.Instance; } return resourceHandler; } } - + TargetFramework targetFramework; public TargetFramework TargetFramework { @@ -350,18 +410,23 @@ namespace MonoDevelop.Projects public TargetRuntime TargetRuntime { get { return Runtime.SystemAssemblyService.DefaultRuntime; } } - + /// <summary> /// Gets the target framework for new projects /// </summary> /// <returns> /// The default target framework identifier. /// </returns> - public virtual TargetFrameworkMoniker GetDefaultTargetFrameworkId () + public TargetFrameworkMoniker GetDefaultTargetFrameworkId () + { + return ProjectExtension.OnGetDefaultTargetFrameworkId (); + } + + protected virtual TargetFrameworkMoniker OnGetDefaultTargetFrameworkId () { return Services.ProjectService.DefaultTargetFramework.Id; } - + /// <summary> /// Returns the default framework for a given format /// </summary> @@ -375,11 +440,25 @@ namespace MonoDevelop.Projects /// This method is used to determine what's the correct target framework for a project /// deserialized using a specific format. /// </remarks> - public virtual TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format) + public TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format) + { + return ProjectExtension.OnGetDefaultTargetFrameworkForFormat (format); + } + + protected virtual TargetFrameworkMoniker OnGetDefaultTargetFrameworkForFormat (FileFormat format) { + switch (format.Id) { + case "MSBuild05": + return TargetFrameworkMoniker.NET_2_0; + case "MSBuild08": + return TargetFrameworkMoniker.NET_2_0; + case "MSBuild10": + case "MSBuild12": + return TargetFrameworkMoniker.NET_4_0; + } return GetDefaultTargetFrameworkId (); } - + public IAssemblyContext AssemblyContext { get { if (composedAssemblyContext == null) { @@ -400,8 +479,17 @@ namespace MonoDevelop.Projects } } - public virtual bool SupportsFramework (TargetFramework framework) + public bool SupportsFramework (TargetFramework framework) + { + return ProjectExtension.OnGetSupportsFramework (framework); + } + + protected virtual bool OnSupportsFramework (TargetFramework framework) { + // DotNetAssemblyProject can only generate assemblies for the regular framework. + // Special frameworks such as Moonlight or MonoTouch must override SupportsFramework. + if (!framework.CanReferenceAssembliesTargetingFramework (TargetFrameworkMoniker.NET_1_1)) + return false; if (LanguageBinding == null) return false; ClrVersion[] versions = LanguageBinding.GetSupportedClrVersions (); @@ -414,7 +502,6 @@ namespace MonoDevelop.Projects return false; } - [ItemProperty(DefaultValue = true)] public bool UsePartialTypes { get { return usePartialTypes; } set { usePartialTypes = value; } @@ -426,16 +513,16 @@ namespace MonoDevelop.Projects composedAssemblyContext.Dispose (); // composedAssemblyContext = null; } - + // languageParameters = null; // privateAssemblyContext = null; // currentRuntimeContext = null; // languageBinding = null; // projectReferences = null; - + Runtime.SystemAssemblyService.DefaultRuntimeChanged -= RuntimeSystemAssemblyServiceDefaultRuntimeChanged; FileService.FileRemoved -= OnFileRemoved; - + base.Dispose (); } @@ -477,7 +564,7 @@ namespace MonoDevelop.Projects // cached and won't take into account unsubscriptions until the next dispatch if (Disposed) return; - + base.OnFileChanged (source, e); foreach (FileEventInfo ei in e) CheckReferenceChange (ei.FileName); @@ -501,24 +588,24 @@ namespace MonoDevelop.Projects this.References.Add (prNew); } } - + internal protected override void PopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration) { base.PopulateOutputFileList (list, configuration); DotNetProjectConfiguration conf = GetConfiguration (configuration) as DotNetProjectConfiguration; - + // Debug info file - + if (conf.DebugMode) { string mdbFile = TargetRuntime.GetAssemblyDebugInfoFile (conf.CompiledOutputName); list.Add (mdbFile); } - + // Generated satellite resource files - + FilePath outputDir = conf.OutputDirectory; string satelliteAsmName = Path.GetFileNameWithoutExtension (conf.CompiledOutputName) + ".resources.dll"; - + HashSet<string> cultures = new HashSet<string> (); foreach (ProjectFile finfo in Files) { if (finfo.Subtype == Subtype.Directory || finfo.BuildAction != BuildAction.EmbeddedResource) @@ -532,7 +619,7 @@ namespace MonoDevelop.Projects } } } - + [ThreadStatic] static int supportReferDistance; [ThreadStatic] @@ -561,13 +648,13 @@ namespace MonoDevelop.Projects //rename the app.config file list.Remove ("app.config"); list.Remove ("App.config"); - + ProjectFile appConfig = Files.FirstOrDefault (f => f.FilePath.FileName.Equals ("app.config", StringComparison.CurrentCultureIgnoreCase)); if (appConfig != null) { string output = GetOutputFileName (configuration).FileName; list.Add (appConfig.FilePath, true, output + ".config"); } - + //collect all the "local copy" references and their attendant files foreach (ProjectReference projectReference in References) { if (!projectReference.LocalCopy || !projectReference.CanSetLocalCopy) @@ -614,7 +701,7 @@ namespace MonoDevelop.Projects } } } - + //Given a filename like foo.it.resx, get 'it', if its //a valid culture //Note: hand-written as this can get called lotsa times @@ -664,14 +751,14 @@ namespace MonoDevelop.Projects return cultureNamesTable; } } - + IEnumerable<string> GetAssemblyRefsRec (string fileName, HashSet<string> visited) { // Recursivelly finds assemblies referenced by the given assembly - + if (!visited.Add (fileName)) yield break; - + if (!File.Exists (fileName)) { string ext = Path.GetExtension (fileName).ToLower (); if (ext == ".dll" || ext == ".exe") @@ -683,7 +770,7 @@ namespace MonoDevelop.Projects else yield break; } - + yield return fileName; foreach (var reference in SystemAssemblyService.GetAssemblyReferences (fileName)) { @@ -705,9 +792,9 @@ namespace MonoDevelop.Projects return newReferenceInformation; } - public override IEnumerable<SolutionItem> GetReferencedItems (ConfigurationSelector configuration) + protected override IEnumerable<SolutionItem> OnGetReferencedItems (ConfigurationSelector configuration) { - List<SolutionItem> items = new List<SolutionItem> (base.GetReferencedItems (configuration)); + var items = new List<SolutionItem> (base.OnGetReferencedItems (configuration)); if (ParentSolution == null) return items; @@ -745,23 +832,24 @@ namespace MonoDevelop.Projects /// </param> public IEnumerable<string> GetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences) { - return Services.ProjectService.GetExtensionChain (this).GetReferencedAssemblies (this, configuration, includeProjectReferences); + return ProjectExtension.OnGetReferencedAssemblies (configuration, includeProjectReferences); } internal protected virtual IEnumerable<string> OnGetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences) { - IAssemblyReferenceHandler handler = this.ItemHandler as IAssemblyReferenceHandler; - if (handler != null) { + if (CheckUseMSBuildEngine (configuration)) { if (includeProjectReferences) { foreach (ProjectReference pref in References.Where (pr => pr.ReferenceType == ReferenceType.Project)) { foreach (string asm in pref.GetReferencedFileNames (configuration)) yield return asm; } } - foreach (string file in handler.GetAssemblyReferences (configuration)) - yield return file; - } - else { + // Get the references list from the msbuild project + RemoteProjectBuilder builder = GetProjectBuilder (); + var configs = GetConfigurations (configuration); + foreach (var r in builder.ResolveAssemblyReferences (configs)) + yield return r; + } else { foreach (ProjectReference pref in References) { if (includeProjectReferences || pref.ReferenceType != ReferenceType.Project) { foreach (string asm in pref.GetReferencedFileNames (configuration)) @@ -772,12 +860,8 @@ namespace MonoDevelop.Projects var config = (DotNetProjectConfiguration)GetConfiguration (configuration); bool noStdLib = false; - if (config != null) { - var parameters = config.CompilationParameters as DotNetConfigurationParameters; - if (parameters != null) { - noStdLib = parameters.NoStdLib; - } - } + if (config != null) + noStdLib = config.CompilationParameters.NoStdLib; // System.Core is an implicit reference if (!noStdLib) { @@ -787,13 +871,13 @@ namespace MonoDevelop.Projects } } - protected internal override void OnSave (IProgressMonitor monitor) + protected internal override Task OnSave (ProgressMonitor monitor) { // Make sure the fx version is sorted out before saving - // to avoid changes in project references while saving + // to avoid changes in project references while saving if (targetFramework == null) targetFramework = Runtime.SystemAssemblyService.GetTargetFramework (GetDefaultTargetFrameworkForFormat (FileFormat)); - base.OnSave (monitor); + return base.OnSave (monitor); } IDotNetLanguageBinding FindLanguage (string name) @@ -839,7 +923,7 @@ namespace MonoDevelop.Projects { if (base.CheckNeedsBuild (configuration)) return true; - + // base.CheckNeedsBuild() checks Project references, but not Assembly, Package, or Custom. DateTime mtime = GetLastBuildTime (configuration); foreach (ProjectReference pref in References) { @@ -875,11 +959,11 @@ namespace MonoDevelop.Projects && String.Compare (Path.GetExtension (file.FilePath), ".resx", StringComparison.OrdinalIgnoreCase) == 0 && MD1DotNetProjectHandler.IsResgenRequired (file.FilePath, config.IntermediateOutputDirectory.Combine (file.ResourceId))); } - + protected internal override DateTime OnGetLastBuildTime (ConfigurationSelector configuration) { var outputBuildTime = base.OnGetLastBuildTime (configuration); - + //if the debug file is newer than the output file, use that as the build time var conf = (DotNetProjectConfiguration) GetConfiguration (configuration); if (GeneratesDebugInfoFile && conf != null && conf.DebugMode) { @@ -896,7 +980,7 @@ namespace MonoDevelop.Projects } return outputBuildTime; } - + public IList<string> GetUserAssemblyPaths (ConfigurationSelector configuration) { if (ParentSolution == null) @@ -908,7 +992,12 @@ namespace MonoDevelop.Projects .Where (d => !string.IsNullOrEmpty (d)).ToList (); } - protected virtual ExecutionCommand CreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration) + public ExecutionCommand CreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration) + { + return ProjectExtension.OnCreateExecutionCommand (configSel, configuration); + } + + internal protected virtual ExecutionCommand OnCreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration) { DotNetExecutionCommand cmd = new DotNetExecutionCommand (configuration.CompiledOutputName); cmd.Arguments = configuration.CommandLineParameters; @@ -919,7 +1008,7 @@ namespace MonoDevelop.Projects return cmd; } - protected internal override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) + protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) { DotNetProjectConfiguration config = (DotNetProjectConfiguration) GetConfiguration (configuration); if (config == null) @@ -931,10 +1020,11 @@ namespace MonoDevelop.Projects return (compileTarget == CompileTarget.Exe || compileTarget == CompileTarget.WinExe) && context.ExecutionHandler.CanExecute (cmd); } - protected internal override List<FilePath> OnGetItemFiles (bool includeReferencedFiles) + protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) { - List<FilePath> col = base.OnGetItemFiles (includeReferencedFiles); + var baseFiles = base.OnGetItemFiles (includeReferencedFiles); if (includeReferencedFiles) { + List<FilePath> col = new List<FilePath> (); foreach (ProjectReference pref in References) { if (pref.ReferenceType == ReferenceType.Assembly) { foreach (var f in pref.GetReferencedFileNames (DefaultConfiguration.Selector)) @@ -945,10 +1035,20 @@ namespace MonoDevelop.Projects if (c.SignAssembly) col.Add (c.AssemblyKeyFile); } + baseFiles = baseFiles.Concat (col); } - return col; + return baseFiles; + } + + internal Task<BuildResult> Compile (ProgressMonitor monitor, BuildData buildData) + { + return ProjectExtension.OnCompile (monitor, buildData); } + protected virtual Task<BuildResult> OnCompile (ProgressMonitor monitor, BuildData buildData) + { + return MD1DotNetProjectHandler.Compile (monitor, this, buildData); + } public override bool IsCompileable (string fileName) { @@ -979,7 +1079,7 @@ namespace MonoDevelop.Projects string defaultNmspc = !string.IsNullOrEmpty (defaultNamespace) ? defaultNamespace : SanitisePotentialNamespace (project.Name) ?? "Application"; - + if (string.IsNullOrEmpty (fileName)) { return defaultNmspc; } @@ -1088,22 +1188,6 @@ namespace MonoDevelop.Projects return BuildAction.DotNetCommonActions; } - internal override void SetItemHandler (ISolutionItemHandler handler) - { - if (ProjectExtensionUtil.GetItemHandler (this) == null) { - // Initial assignment of the item handler - base.SetItemHandler (handler); - return; - } - IResourceHandler rh = ResourceHandler; - - base.SetItemHandler (handler); - resourceHandler = null; - // A change in the file format may imply a change in the resource naming policy. - // Make sure that the resource Id don't change. - MigrateResourceIds (rh, ResourceHandler); - } - protected override void OnEndLoad () { // The resource handler policy may have changed after loading, so reset any @@ -1112,7 +1196,7 @@ namespace MonoDevelop.Projects // Just after loading, the resource Ids are using the file format's policy. // They have to be converted to the new policy - IResourceHandler handler = ItemHandler as IResourceHandler; + IResourceHandler handler = GetService<IResourceHandler> (); if (handler != null) MigrateResourceIds (handler, ResourceHandler); @@ -1172,13 +1256,13 @@ namespace MonoDevelop.Projects internal void NotifyReferenceRemovedFromProject (ProjectReference reference) { NotifyModified ("References"); - OnReferenceRemovedFromProject (new ProjectReferenceEventArgs (this, reference)); + ProjectExtension.OnReferenceRemovedFromProject (new ProjectReferenceEventArgs (this, reference)); } internal void NotifyReferenceAddedToProject (ProjectReference reference) { NotifyModified ("References"); - OnReferenceAddedToProject (new ProjectReferenceEventArgs (this, reference)); + ProjectExtension.OnReferenceAddedToProject (new ProjectReferenceEventArgs (this, reference)); } protected virtual void OnReferenceRemovedFromProject (ProjectReferenceEventArgs e) @@ -1205,7 +1289,7 @@ namespace MonoDevelop.Projects CheckReferenceChange (ei.FileName); } - protected override void DoExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + protected async override Task DoExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { DotNetProjectConfiguration dotNetProjectConfig = GetConfiguration (configuration) as DotNetProjectConfiguration; monitor.Log.WriteLine (GettextCatalog.GetString ("Running {0} ...", dotNetProjectConfig.CompiledOutputName)); @@ -1213,8 +1297,6 @@ namespace MonoDevelop.Projects IConsole console = dotNetProjectConfig.ExternalConsole ? context.ExternalConsoleFactory.CreateConsole (!dotNetProjectConfig.PauseConsoleOutput) : context.ConsoleFactory.CreateConsole (!dotNetProjectConfig.PauseConsoleOutput); - - AggregatedOperationMonitor aggregatedOperationMonitor = new AggregatedOperationMonitor (monitor); try { try { @@ -1227,14 +1309,16 @@ namespace MonoDevelop.Projects return; } - IProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute (executionCommand, console); - aggregatedOperationMonitor.AddOperation (asyncOp); - asyncOp.WaitForCompleted (); + ProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute (executionCommand, console); + var stopper = monitor.CancellationToken.Register (asyncOp.Cancel); + + await asyncOp.Task; + + stopper.Dispose (); monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", asyncOp.ExitCode)); } finally { console.Dispose (); - aggregatedOperationMonitor.Dispose (); } } catch (Exception ex) { LoggingService.LogError (string.Format ("Cannot execute \"{0}\"", dotNetProjectConfig.CompiledOutputName), ex); @@ -1242,32 +1326,158 @@ namespace MonoDevelop.Projects } } - public void AddImportIfMissing (string name, string condition) + + protected override void OnReadProjectHeader (ProgressMonitor monitor, MSBuildProject msproject) { - importsAdded.Add (new DotNetProjectImport (name, condition)); + base.OnReadProjectHeader (monitor, msproject); + + compileTarget = msproject.EvaluatedProperties.GetValue<CompileTarget> ("OutputType"); + defaultNamespace = msproject.EvaluatedProperties.GetValue ("RootNamespace", string.Empty); + usePartialTypes = msproject.EvaluatedProperties.GetValue ("UsePartialTypes", true); + + string frameworkIdentifier = msproject.EvaluatedProperties.GetValue ("TargetFrameworkIdentifier"); + string frameworkVersion = msproject.EvaluatedProperties.GetValue ("TargetFrameworkVersion"); + string frameworkProfile = msproject.EvaluatedProperties.GetValue ("TargetFrameworkProfile"); + + //determine the default target framework from the project type's default + //overridden by the components in the project + var def = GetDefaultTargetFrameworkForFormat (GetFileFormat (GetToolsFormat ())); + var targetFx = new TargetFrameworkMoniker ( + string.IsNullOrEmpty (frameworkIdentifier)? def.Identifier : frameworkIdentifier, + string.IsNullOrEmpty (frameworkVersion)? def.Version : frameworkVersion, + string.IsNullOrEmpty (frameworkProfile)? def.Profile : frameworkProfile); + + + string fx = ExtendedProperties ["InternalTargetFrameworkVersion"] as string; + if (!string.IsNullOrEmpty (fx)) { + targetFx = TargetFrameworkMoniker.Parse (fx); + ExtendedProperties.Remove ("InternalTargetFrameworkVersion"); + } + + TargetFramework = Runtime.SystemAssemblyService.GetTargetFramework (targetFx); } - public void RemoveImport (string name) + protected override void OnWriteProjectHeader (ProgressMonitor monitor, MSBuildProject msproject) { - importsRemoved.Add (new DotNetProjectImport (name)); + base.OnWriteProjectHeader (monitor, msproject); + + IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup (); + + globalGroup.SetValue ("OutputType", compileTarget); + globalGroup.SetValue ("RootNamespace", defaultNamespace, string.Empty); + globalGroup.SetValue ("UsePartialTypes", usePartialTypes, true); } - List <DotNetProjectImport> importsAdded = new List<DotNetProjectImport> (); + protected override void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject) + { + base.OnWriteProject (monitor, msproject); + + var toolsFormat = GetToolsFormat (); + var moniker = TargetFramework.Id; + bool supportsMultipleFrameworks = toolsFormat.SupportsMonikers || toolsFormat.SupportedFrameworks.Length > 0; + var def = GetDefaultTargetFrameworkForFormat (GetFileFormat (toolsFormat)); + + IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup (); - internal IList<DotNetProjectImport> ImportsAdded { - get { return importsAdded; } + // If the format only supports one fx version, or the version is the default, there is no need to store it. + // However, is there is already a value set, do not remove it. + if (supportsMultipleFrameworks) { + globalGroup.SetValue ("TargetFrameworkVersion", "v" + moniker.Version, "v" + def.Version, true); + } + + if (toolsFormat.SupportsMonikers) { + globalGroup.SetValue ("TargetFrameworkIdentifier", moniker.Identifier, def.Identifier, true); + globalGroup.SetValue ("TargetFrameworkProfile", moniker.Profile, def.Profile, true); + } } - List <DotNetProjectImport> importsRemoved = new List<DotNetProjectImport> (); + protected override void OnWriteConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet pset) + { + base.OnWriteConfiguration (monitor, config, pset); + if (pset.Project.IsNewProject) + pset.SetValue ("ErrorReport", "prompt"); + + } - internal IList<DotNetProjectImport> ImportsRemoved { - get { return importsRemoved; } + FileFormat GetFileFormat (MSBuildFileFormat fmt) + { + return new FileFormat (fmt, fmt.Id, fmt.Name); } - public void ImportsSaved () + internal class DefaultDotNetProjectExtension: DotNetProjectExtension { - importsAdded.Clear (); - importsRemoved.Clear (); + internal protected override bool IsLibraryBasedProjectType { + get { + return false; + } + } + + internal protected override bool GeneratesDebugInfoFile { + get { + return true; + } + } + + internal protected override bool SupportsPartialTypes { + get { + return Project.SupportsPartialTypes; + } + } + + + internal protected override bool OnGetCanReferenceProject (DotNetProject targetProject, out string reason) + { + return Project.CheckCanReferenceProject (targetProject, out reason); + } + + internal protected override string OnGetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo) + { + return Project.OnGetDefaultTargetPlatform (projectCreateInfo); + } + + internal protected override IEnumerable<string> OnGetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences) + { + return Project.OnGetReferencedAssemblies (configuration, includeProjectReferences); + } + + internal protected override ExecutionCommand OnCreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration) + { + return Project.OnCreateExecutionCommand (configSel, configuration); + } + + internal protected override void OnReferenceRemovedFromProject (ProjectReferenceEventArgs e) + { + Project.OnReferenceRemovedFromProject (e); + } + + internal protected override void OnReferenceAddedToProject (ProjectReferenceEventArgs e) + { + Project.OnReferenceAddedToProject (e); + } + + internal protected override Task<BuildResult> OnCompile (ProgressMonitor monitor, BuildData buildData) + { + return Project.OnCompile (monitor, buildData); + } + + #region Framework management + + internal protected override TargetFrameworkMoniker OnGetDefaultTargetFrameworkId () + { + return Project.OnGetDefaultTargetFrameworkId (); + } + + internal protected override TargetFrameworkMoniker OnGetDefaultTargetFrameworkForFormat (FileFormat format) + { + return Project.OnGetDefaultTargetFrameworkForFormat (format); + } + + internal protected override bool OnGetSupportsFramework (TargetFramework framework) + { + return Project.OnSupportsFramework (framework); + } + + #endregion } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectBinding.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectBinding.cs deleted file mode 100644 index e2e26591cb..0000000000 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectBinding.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -// DotNetProjectBinding.cs -// -// Author: -// Lluis Sanchez Gual -// -// Copyright (C) 2005 Novell, Inc (http://www.novell.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; -using System.Xml; -using MonoDevelop.Core.Serialization; -using MonoDevelop.Core; - -namespace MonoDevelop.Projects -{ - public class DotNetProjectBinding : IProjectBinding - { - public virtual string Name { - get { return "DotNet"; } - } - - public Project CreateProject (ProjectCreateInformation info, XmlElement projectOptions) - { - string lang = projectOptions.GetAttribute ("language"); - return CreateProject (lang, info, projectOptions); - } - - protected virtual DotNetProject CreateProject (string languageName, ProjectCreateInformation info, XmlElement projectOptions) - { - return new DotNetAssemblyProject (languageName, info, projectOptions); - } - - public Project CreateSingleFileProject (string file) - { - IDotNetLanguageBinding binding = LanguageBindingService.GetBindingPerFileName (file) as IDotNetLanguageBinding; - if (binding != null) { - ProjectCreateInformation info = new ProjectCreateInformation (); - info.ProjectName = Path.GetFileNameWithoutExtension (file); - info.SolutionPath = Path.GetDirectoryName (file); - info.ProjectBasePath = Path.GetDirectoryName (file); - Project project = CreateProject (binding.Language, info, null); - project.Files.Add (new ProjectFile (file)); - return project; - } - return null; - } - - public bool CanCreateSingleFileProject (string file) - { - IDotNetLanguageBinding binding = LanguageBindingService.GetBindingPerFileName (file) as IDotNetLanguageBinding; - return binding != null; - } - - } -} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectConfiguration.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectConfiguration.cs index ed6bb65fa5..5d359650c8 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectConfiguration.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectConfiguration.cs @@ -35,6 +35,7 @@ using MonoDevelop.Core.Serialization; using MonoDevelop.Core.Assemblies; using MonoDevelop.Core.StringParsing; using System.Collections.Generic; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { @@ -47,14 +48,10 @@ namespace MonoDevelop.Projects public class DotNetProjectConfiguration: ProjectConfiguration { - [MonoDevelop.Projects.Formats.MSBuild.MergeToProject] - [ItemProperty ("AssemblyName")] string assembly; - - ConfigurationParameters compilationParameters; - string sourcePath; - + DotNetCompilerParameters compilationParameters; + public DotNetProjectConfiguration () { } @@ -63,32 +60,49 @@ namespace MonoDevelop.Projects { } - [MonoDevelop.Projects.Formats.MSBuild.MergeToProject] - [ItemProperty("SignAssembly", DefaultValue = false)] + internal protected override void Read (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + base.Read (pset, format); + + assembly = pset.GetValue ("AssemblyName"); + signAssembly = pset.GetValue<bool> ("SignAssembly"); + delaySign = pset.GetValue<bool> ("DelaySign"); + assemblyKeyFile = pset.GetPathValue ("AssemblyOriginatorKeyFile"); + if (string.IsNullOrEmpty (assemblyKeyFile)) + assemblyKeyFile = pset.GetPathValue ("AssemblyKeyFile"); + if (compilationParameters != null) + ((IMSBuildDataObject)compilationParameters).Read (pset, format); + } + + internal protected override void Write (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + base.Write (pset, format); + pset.SetValue ("AssemblyName", assembly, mergeToMainGroup: true); + pset.SetValue ("SignAssembly", signAssembly, defaultValue:false, mergeToMainGroup: true); + pset.SetValue ("DelaySign", delaySign, defaultValue:false, mergeToMainGroup:true); + pset.SetValue ("AssemblyOriginatorKeyFile", assemblyKeyFile, mergeToMainGroup:true); + if (compilationParameters != null) + ((IMSBuildDataObject)compilationParameters).Write (pset, format); + } + private bool signAssembly = false; public bool SignAssembly { get { return signAssembly; } set { signAssembly = value; } } - [MonoDevelop.Projects.Formats.MSBuild.MergeToProject] - [ItemProperty("DelaySign", DefaultValue = false)] private bool delaySign = false; public bool DelaySign { get { return delaySign; } set { delaySign = value; } } - [MonoDevelop.Projects.Formats.MSBuild.MergeToProject] - [ProjectPathItemProperty("AssemblyKeyFile", ReadOnly=true)] internal string OldAssemblyKeyFile { set { assemblyKeyFile = value; } } - [MonoDevelop.Projects.Formats.MSBuild.MergeToProject] - [ProjectPathItemProperty("AssemblyOriginatorKeyFile", DefaultValue = "")] - private string assemblyKeyFile = ""; - public string AssemblyKeyFile { + private FilePath assemblyKeyFile = FilePath.Empty; + public FilePath AssemblyKeyFile { get { return assemblyKeyFile; } set { assemblyKeyFile = value; } } @@ -149,8 +163,7 @@ namespace MonoDevelop.Projects } } - [ItemProperty ("CodeGeneration")] - public ConfigurationParameters CompilationParameters { + public DotNetCompilerParameters CompilationParameters { get { return compilationParameters; } set { compilationParameters = value; @@ -159,16 +172,6 @@ namespace MonoDevelop.Projects } } - public ProjectParameters ProjectParameters { - get { - DotNetProject dnp = ParentItem as DotNetProject; - if (dnp != null) - return dnp.LanguageParameters; - else - return null; - } - } - public FilePath CompiledOutputName { get { FilePath fullPath = OutputDirectory.Combine (OutputAssembly); @@ -206,7 +209,7 @@ namespace MonoDevelop.Projects } } - public class UnknownCompilationParameters: ConfigurationParameters, IExtendedDataItem + public class UnknownCompilationParameters: DotNetCompilerParameters, IExtendedDataItem { readonly Hashtable table = new Hashtable (); diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectExtension.cs new file mode 100644 index 0000000000..09f2a6b871 --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectExtension.cs @@ -0,0 +1,132 @@ +// +// DotNetProjectExtension.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 System.Collections.Generic; +using MonoDevelop.Core.Assemblies; +using MonoDevelop.Core.Execution; +using MonoDevelop.Core; +using System.Threading.Tasks; + +namespace MonoDevelop.Projects +{ + public class DotNetProjectExtension: ProjectExtension + { + #region Project properties + + DotNetProjectExtension next; + + internal protected override void InitializeChain (ChainedExtension next) + { + base.InitializeChain (next); + this.next = FindNextImplementation<DotNetProjectExtension> (next); + } + + internal protected override bool SupportsObject (WorkspaceObject item) + { + return base.SupportsObject (item) && (item is DotNetProject); + } + + new public DotNetProject Project { + get { return (DotNetProject)base.Item; } + } + + + internal protected virtual bool IsLibraryBasedProjectType { + get { + return next.IsLibraryBasedProjectType; + } + } + + internal protected virtual bool GeneratesDebugInfoFile { + get { + return next.GeneratesDebugInfoFile; + } + } + + internal protected virtual bool SupportsPartialTypes { + get { + return next.SupportsPartialTypes; + } + } + + #endregion + + internal protected virtual bool OnGetCanReferenceProject (DotNetProject targetProject, out string reason) + { + return next.OnGetCanReferenceProject (targetProject, out reason); + } + + internal protected virtual string OnGetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo) + { + return next.OnGetDefaultTargetPlatform (projectCreateInfo); + } + + internal protected virtual IEnumerable<string> OnGetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences) + { + return next.OnGetReferencedAssemblies (configuration, includeProjectReferences); + } + + internal protected virtual ExecutionCommand OnCreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration) + { + return next.OnCreateExecutionCommand (configSel, configuration); + } + + internal protected virtual void OnReferenceRemovedFromProject (ProjectReferenceEventArgs e) + { + next.OnReferenceRemovedFromProject (e); + } + + internal protected virtual void OnReferenceAddedToProject (ProjectReferenceEventArgs e) + { + next.OnReferenceAddedToProject (e); + } + + #region Framework management + + internal protected virtual TargetFrameworkMoniker OnGetDefaultTargetFrameworkId () + { + return next.OnGetDefaultTargetFrameworkId (); + } + + internal protected virtual TargetFrameworkMoniker OnGetDefaultTargetFrameworkForFormat (FileFormat format) + { + return next.OnGetDefaultTargetFrameworkForFormat (format); + } + + internal protected virtual bool OnGetSupportsFramework (TargetFramework framework) + { + return next.OnGetSupportsFramework (framework); + } + + internal protected virtual Task<BuildResult> OnCompile (ProgressMonitor monitor, BuildData buildData) + { + return next.OnCompile (monitor, buildData); + } + + #endregion + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ExtensionChain.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ExtensionChain.cs new file mode 100644 index 0000000000..9916adc7bd --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ExtensionChain.cs @@ -0,0 +1,69 @@ +// +// ExtensionChain.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 System.Collections.Generic; + +namespace MonoDevelop.Projects +{ + public class ExtensionChain + { + ChainedExtension first; + Dictionary<Type,ChainedExtension> chains = new Dictionary<Type, ChainedExtension> (); + + public static ExtensionChain Create<T> (T[] extensions) where T:ChainedExtension + { + for (int n = extensions.Length - 2; n >= 0; n--) + extensions [n].Init (extensions [n + 1]); + return new ExtensionChain { + first = extensions[0] + }; + } + + public T GetExtension<T> () where T:ChainedExtension + { + ChainedExtension e; + if (!chains.TryGetValue (typeof(T), out e)) { + chains [typeof(T)] = e = ChainedExtension.FindNextImplementation<T> (first); + } + return (T)e; + } + + public IEnumerable<ChainedExtension> GetAllExtensions () + { + var e = first; + while (e != null) { + yield return e; + e = e.Next; + } + } + + public void Dispose () + { + first.DisposeChain (); + } + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/GenericProject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/GenericProject.cs index 9e14d17bb6..7e324914a0 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/GenericProject.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/GenericProject.cs @@ -49,9 +49,9 @@ namespace MonoDevelop.Projects return conf; } - public override IEnumerable<string> GetProjectTypes () + protected override void OnGetProjectTypes (HashSet<string> types) { - yield return "GenericProject"; + types.Add ("GenericProject"); } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/GenericProjectBinding.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/GenericProjectBinding.cs deleted file mode 100644 index a0adbabee8..0000000000 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/GenericProjectBinding.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// MakefileProjectBinding.cs -// -// Author: -// Lluis Sanchez Gual -// -// Copyright (C) 2007 Novell, Inc (http://www.novell.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; -using System.Xml; -using MonoDevelop.Core.Serialization; -using MonoDevelop.Core; -using MonoDevelop.Projects; - -namespace MonoDevelop.Projects -{ - public class GenericProjectBinding : IProjectBinding - { - public virtual string Name { - get { return "GenericProject"; } - } - - public Project CreateProject (ProjectCreateInformation info, XmlElement projectOptions) - { - return new GenericProject (info, projectOptions); - } - - public Project CreateSingleFileProject (string file) - { - return null; - } - - public bool CanCreateSingleFileProject (string file) - { - return false; - } - } -} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IBuildTarget.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IBuildTarget.cs index 46f53edd81..bc882c60d3 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IBuildTarget.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IBuildTarget.cs @@ -29,19 +29,17 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using MonoDevelop.Core; +using System.Threading.Tasks; namespace MonoDevelop.Projects { - public interface IBuildTarget: IWorkspaceObject + public interface IBuildTarget { - BuildResult RunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration); - bool SupportsTarget (string target); - void Execute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration); + Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector configuration, bool buildReferencedTargets = false); + Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration); + Task Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration); bool CanExecute (ExecutionContext context, ConfigurationSelector configuration); bool NeedsBuilding (ConfigurationSelector configuration); - void SetNeedsBuilding (bool needsBuilding, ConfigurationSelector configuration); - -// ReadOnlyCollection<string> GetConfigurations (); -// event EventHandler ConfigurationsChanged; + string Name { get; } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IDotNetLanguageBinding.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IDotNetLanguageBinding.cs index 618219d4a3..9b30606afb 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IDotNetLanguageBinding.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IDotNetLanguageBinding.cs @@ -38,10 +38,9 @@ namespace MonoDevelop.Projects get; } - ConfigurationParameters CreateCompilationParameters (XmlElement projectOptions); - ProjectParameters CreateProjectParameters (XmlElement projectOptions); + DotNetCompilerParameters CreateCompilationParameters (XmlElement projectOptions); - BuildResult Compile (ProjectItemCollection items, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor); + BuildResult Compile (ProjectItemCollection items, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, ProgressMonitor monitor); ClrVersion[] GetSupportedClrVersions (); diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectParameters.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IMSBuildDataObject.cs index 013b99f441..2c94b3c395 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/DotNetProjectParameters.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IMSBuildDataObject.cs @@ -1,21 +1,21 @@ -// -// DotNetProjectParameters.cs -// +// +// IProjectConfigurationData.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,18 +23,15 @@ // 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.Formats.MSBuild; namespace MonoDevelop.Projects { - /// <summary> - /// This is the base class for project parameter classes. - /// </summary> - public class DotNetProjectParameters: ProjectParameters + public interface IMSBuildDataObject { - public virtual bool DefaultNamespaceIsImplicit { - get { return false; } - } + void Read (IMSBuildPropertySet pset, MSBuildFileFormat format); + void Write (IMSBuildPropertySet pset, MSBuildFileFormat format); } } + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SimpleProjectItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IProject.cs index 633e82f83d..286b4abe95 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SimpleProjectItem.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IProject.cs @@ -1,21 +1,21 @@ -// -// SimpleProjectItem.cs -// +// +// IProject.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,15 +23,12 @@ // 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; namespace MonoDevelop.Projects { - public class SimpleProjectItem: ProjectItem + public interface IProject2 { - [ItemProperty ("Include")] - public string Include { get; set; } } } + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IProjectBinding.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IProjectBinding.cs deleted file mode 100644 index 5c0ce972f9..0000000000 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IProjectBinding.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -// IProjectBinding.cs -// -// Author: -// Lluis Sanchez Gual - -// -// Copyright (C) 2005 Novell, Inc (http://www.novell.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; -using System.Xml; - -namespace MonoDevelop.Projects -{ - public interface IProjectBinding - { - /// <remarks> - /// Returns the project type name - /// </remarks> - string Name { get; } - - /// <remarks> - /// Creates a Project out of the given ProjetCreateInformation object. - /// Each project binding must provide a representation of the project - /// it 'controls'. - /// </remarks> - Project CreateProject (ProjectCreateInformation info, XmlElement projectOptions); - - /// <remarks> - /// Creates a Project for a single source file. If the file is not - /// valid for this project type, it must return null. - /// </remarks> - Project CreateSingleFileProject (string sourceFile); - - bool CanCreateSingleFileProject (string sourceFile); - } -} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IPropertySet.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IPropertySet.cs new file mode 100644 index 0000000000..56ccd1f3c8 --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IPropertySet.cs @@ -0,0 +1,49 @@ +// +// IPropertySet.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 System.Xml; +using MonoDevelop.Core; +using System.Xml.Linq; + +namespace MonoDevelop.Projects +{ + public interface IPropertySet + { + + void SetValue (string name, string value, string defaultValue = null, bool preserveExistingCase = false, bool mergeToMainGroup = false, string condition = null, bool persist = true); + void SetValue (string name, XmlElement elem, bool mergeToMainGroup = false, string condition = null, bool persist = true); + void SetValue (string name, XElement elem, bool mergeToMainGroup = false, string condition = null, bool persist = true); + void SetValue (string name, FilePath value, FilePath defaultValue = default(FilePath), bool relativeToProject = true, bool mergeToMainGroup = false, string condition = null, bool persist = true); + void SetValue (string name, bool value, bool? defaultValue = false, bool mergeToMainGroup = false, string condition = null, bool persist = true); + + string GetValue (string name, string defaultValue = null); + XElement GetXmlValue (string name); + FilePath GetPathValue (string name, FilePath defaultValue = default(FilePath), bool relativeToProject = true); + bool GetBoolValue (string name, bool defaultValue = false); + + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ItemConfiguration.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ItemConfiguration.cs index 32e1e1316e..8956f4feef 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ItemConfiguration.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ItemConfiguration.cs @@ -32,6 +32,7 @@ using System.Collections.ObjectModel; using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; using MonoDevelop.Core; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { @@ -107,7 +108,7 @@ namespace MonoDevelop.Projects public CustomCommandCollection CustomCommands { get { return customCommands; } } - + public object Clone() { ItemConfiguration conf = (ItemConfiguration) Activator.CreateInstance (GetType ()); diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/LanguageBindingService.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/LanguageBindingService.cs index f2823eeeb3..61b04d8b89 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/LanguageBindingService.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/LanguageBindingService.cs @@ -48,9 +48,6 @@ namespace MonoDevelop.Projects object par = dotNetBinding.CreateCompilationParameters (null); if (par != null) Services.ProjectService.DataContext.IncludeType (par.GetType ()); - par = dotNetBinding.CreateProjectParameters (null); - if (par != null) - Services.ProjectService.DataContext.IncludeType (par.GetType ()); } break; case ExtensionChange.Remove: diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/PortableDotNetProject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/PortableDotNetProjectFlavor.cs index 7903a6152a..4a30eee279 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/PortableDotNetProject.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/PortableDotNetProjectFlavor.cs @@ -1,20 +1,21 @@ -// -// PortableDotNetProject.cs -// -// Author: Jeffrey Stedfast <jeff@xamarin.com> -// -// Copyright (c) 2012 Xamarin Inc. -// +// +// PortableDotNetProjectFlavor.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 @@ -22,57 +23,39 @@ // 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.Xml; -using MonoDevelop.Core; +using System.Collections.Generic; using MonoDevelop.Core.Assemblies; using System.Linq; -using System.Collections.Generic; namespace MonoDevelop.Projects { - public class PortableDotNetProject : DotNetProject + public class PortableDotNetProjectFlavor: DotNetProjectExtension { - public PortableDotNetProject () - { - } - - public PortableDotNetProject (string languageName) : base (languageName) - { - } - - public PortableDotNetProject (string languageName, ProjectCreateInformation projectCreateInfo, XmlElement projectOptions) - : base (languageName, projectCreateInfo, projectOptions) + internal protected override void OnGetProjectTypes (HashSet<string> types) { + types.Add ("PortableDotNet"); } - public override IEnumerable<string> GetProjectTypes () - { - yield return "PortableDotNet"; - foreach (var t in base.GetProjectTypes ()) - yield return t; - } - - public override bool SupportsFormat (FileFormat format) + internal protected override bool OnGetSupportsFormat (FileFormat format) { int version; - + if (!format.Id.StartsWith ("MSBuild", StringComparison.Ordinal)) return false; - + if (!int.TryParse (format.Id.Substring ("MSBuild".Length), out version)) return false; - + return version >= 10; } - - public override bool SupportsFramework (TargetFramework framework) + + internal protected override bool OnGetSupportsFramework (TargetFramework framework) { return framework.Id.Identifier == TargetFrameworkMoniker.ID_PORTABLE; } - - public override TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (FileFormat format) + + internal protected override TargetFrameworkMoniker OnGetDefaultTargetFrameworkForFormat (FileFormat format) { // Note: This value is used only when serializing the TargetFramework to the .csproj file. // Any component of the TargetFramework that is different from this base TargetFramework @@ -82,19 +65,20 @@ namespace MonoDevelop.Projects // TargetFrameworkVersion and TargetFrameworkProfile values will be serialized. return new TargetFrameworkMoniker (".NETPortable", "1.0"); } - - public override TargetFrameworkMoniker GetDefaultTargetFrameworkId () + + internal protected override TargetFrameworkMoniker OnGetDefaultTargetFrameworkId () { // Profile78 includes .NET 4.5+, Windows Phone 8, and Xamarin.iOS/Android, so make that our default. // Note: see also: PortableLibrary.xpt.xml return new TargetFrameworkMoniker (".NETPortable", "4.5", "Profile78"); } - protected internal override IEnumerable<string> OnGetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences) + internal protected override IEnumerable<string> OnGetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences) { var res = base.OnGetReferencedAssemblies (configuration, includeProjectReferences); - var asms = TargetRuntime.AssemblyContext.GetAssemblies (TargetFramework).Where (a => a.Package.IsFrameworkPackage).Select (a => a.Location); + var asms = Project.TargetRuntime.AssemblyContext.GetAssemblies (Project.TargetFramework).Where (a => a.Package.IsFrameworkPackage).Select (a => a.Location); return res.Concat (asms).Distinct (); } } } + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Project.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Project.cs index b3bf2233e3..ce145e9c78 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Project.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Project.cs @@ -37,6 +37,14 @@ using MonoDevelop; using MonoDevelop.Core; using MonoDevelop.Core.Serialization; using MonoDevelop.Projects; +using System.Threading.Tasks; +using MonoDevelop.Projects.Formats.MSBuild; +using System.Xml; +using MonoDevelop.Core.Instrumentation; +using MonoDevelop.Core.Assemblies; +using MonoDevelop.Projects.Extensions; +using System.Threading; +using Mono.Addins; namespace MonoDevelop.Projects @@ -48,27 +56,200 @@ namespace MonoDevelop.Projects /// This is the base class for MonoDevelop projects. A project is a solution item which has a list of /// source code files and which can be built to generate an output. /// </remarks> - [DataInclude(typeof(ProjectFile))] - [ProjectModelDataItem(FallbackType = typeof(UnknownProject))] - public abstract class Project : SolutionEntityItem + public class Project : SolutionItem { + string[] flavorGuids = new string[0]; string[] buildActions; + MSBuildProject sourceProject; + + string productVersion; + string schemaVersion; + bool modifiedInMemory; + + List<string> defaultImports = new List<string> (); protected Project () { FileService.FileChanged += OnFileChanged; + Runtime.SystemAssemblyService.DefaultRuntimeChanged += OnDefaultRuntimeChanged; files = new ProjectFileCollection (); Items.Bind (files); DependencyResolutionEnabled = true; } - + + protected Project (params string[] flavorGuids): this() + { + this.flavorGuids = flavorGuids; + } + + protected Project (string[] flavorIds, MSBuildProject sourceProject): this(flavorIds) + { + } + + protected Project (ProjectCreateInformation projectCreateInfo, XmlElement projectOptions): this() + { + var ids = projectOptions != null ? projectOptions.GetAttribute ("flavorIds") : null; + if (!string.IsNullOrEmpty (ids)) { + this.flavorGuids = ids.Split (new [] {';'}, StringSplitOptions.RemoveEmptyEntries); + } + } + + internal class CreationContext + { + static object theLock = new object (); + public MSBuildProject Project { get; set; } + public string TypeGuid { get; set; } + + internal static void LockContext (MSBuildProject p, string typeGuid) + { + Monitor.Enter (theLock); + Current = new CreationContext (); + Current.Project = p; + Current.TypeGuid = typeGuid; + } + + internal static void UnlockContext () + { + Current = null; + Monitor.Exit (theLock); + } + + public static CreationContext Current { get; private set; } + } + + protected override void OnInitialize () + { + base.OnInitialize (); + + if (CreationContext.Current != null) { + + if (IsExtensionChainCreated) + throw new InvalidOperationException ("Extension chain already created for this object"); + + TypeGuid = CreationContext.Current.TypeGuid; + this.sourceProject = CreationContext.Current.Project; + + IMSBuildPropertySet globalGroup = sourceProject.GetGlobalPropertyGroup (); + string projectTypeGuids = globalGroup.GetValue ("ProjectTypeGuids"); + + if (projectTypeGuids != null) { + var subtypeGuids = new List<string> (); + foreach (string guid in projectTypeGuids.Split (';')) { + string sguid = guid.Trim (); + if (sguid.Length > 0 && string.Compare (sguid, CreationContext.Current.TypeGuid, StringComparison.OrdinalIgnoreCase) != 0) + subtypeGuids.Add (guid); + } + flavorGuids = subtypeGuids.ToArray (); + } + } + } + + protected override void OnExtensionChainInitialized () + { + base.OnExtensionChainInitialized (); + if (CreationContext.Current != null) + FileName = CreationContext.Current.Project.FileName; + } + + void OnDefaultRuntimeChanged (object o, EventArgs args) + { + // If the default runtime changes, the project builder for this project may change + // so it has to be created again. + CleanupProjectBuilder (); + } + + public IEnumerable<string> FlavorGuids { + get { return flavorGuids; } + } + + public List<string> DefaultImports { + get { return defaultImports; } + } + + public string ToolsVersion { get; private set; } + + internal bool CheckAllFlavorsSupported () + { + return FlavorGuids.All (g => ProjectExtension.SupportsFlavor (g)); + } + + ProjectExtension projectExtension; + ProjectExtension ProjectExtension { + get { + if (projectExtension == null) + projectExtension = ExtensionChain.GetExtension<ProjectExtension> (); + return projectExtension; + } + } + + /// <summary>Whether to use the MSBuild engine by default.</summary> + internal bool UseMSBuildEngineByDefault { get; set; } + + /// <summary>Forces the MSBuild engine to be used.</summary> + internal bool RequireMSBuildEngine { get; set; } + + protected override void OnModified (SolutionItemModifiedEventArgs args) + { + if (!Loading) + modifiedInMemory = true; + base.OnModified (args); + } + + protected override Task OnLoad (ProgressMonitor monitor) + { + MSBuildProject p = sourceProject; + sourceProject = null; + + return Task.Factory.StartNew (delegate { + if (p == null) + p = MSBuildProject.LoadAsync (FileName).Result; + IMSBuildPropertySet globalGroup = p.GetGlobalPropertyGroup (); + // Avoid crash if there is not global group + if (globalGroup == null) + p.AddNewPropertyGroup (false); + + try { + ProjectExtensionUtil.BeginLoadOperation (); + ReadProject (monitor, p); + } finally { + ProjectExtensionUtil.EndLoadOperation (); + } + }); + } + + internal protected override Task OnSave (ProgressMonitor monitor) + { + modifiedInMemory = false; + + return Task.Factory.StartNew (delegate { + var msproject = WriteProject (monitor); + if (msproject == null) + return; + + // Don't save the file to disk if the content did not change + msproject.Save (FileName); + + if (projectBuilder != null) + projectBuilder.Refresh (); + }); + } + + protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions () + { + return base.CreateDefaultExtensions ().Concat (Enumerable.Repeat (new DefaultMSBuildProjectExtension (), 1)); + } + + internal protected override IEnumerable<string> GetItemTypeGuids () + { + return base.GetItemTypeGuids ().Concat (flavorGuids); + } + /// <summary> /// Description of the project. /// </summary> - [ItemProperty("Description", DefaultValue = "")] private string description = ""; public string Description { - get { return description; } + get { return description ?? ""; } set { description = value; NotifyModified ("Description"); @@ -86,7 +267,7 @@ namespace MonoDevelop.Projects /// </param> public virtual bool IsCompileable (string fileName) { - return false; + return ProjectExtension.OnGetIsCompileable (fileName); } /// <summary> @@ -97,7 +278,6 @@ namespace MonoDevelop.Projects } private ProjectFileCollection files; - [ProjectPathItemProperty ("BaseIntermediateOutputPath")] FilePath baseIntermediateOutputPath; public virtual FilePath BaseIntermediateOutputPath { @@ -129,7 +309,31 @@ namespace MonoDevelop.Projects /// <summary> /// Gets the project type and its base types. /// </summary> - public abstract IEnumerable<string> GetProjectTypes (); + public IEnumerable<string> GetProjectTypes () + { + var types = new HashSet<string> (); + ProjectExtension.OnGetProjectTypes (types); + return types; + } + + protected virtual void OnGetProjectTypes (HashSet<string> types) + { + } + + public bool HasFlavor<T> () + { + return GetService (typeof(T)) != null; + } + + public T GetFlavor<T> () where T:ProjectExtension + { + return (T) GetService (typeof(T)); + } + + internal IEnumerable<ProjectExtension> GetFlavors () + { + return ExtensionChain.GetAllExtensions ().OfType<ProjectExtension> (); + } /// <summary> /// Gets or sets the icon of the project. @@ -138,10 +342,15 @@ namespace MonoDevelop.Projects /// The stock icon. /// </value> public virtual IconId StockIcon { - get { return stockIcon; } + get { + if (stockIcon != null) + return stockIcon.Value; + else + return ProjectExtension.StockIcon; + } set { this.stockIcon = value; NotifyModified ("StockIcon"); } } - IconId stockIcon = "md-project"; + IconId? stockIcon; /// <summary> /// List of languages that this project supports @@ -150,7 +359,7 @@ namespace MonoDevelop.Projects /// The identifiers of the supported languages. /// </value> public virtual string[] SupportedLanguages { - get { return new String[] { "" }; } + get { return ProjectExtension.SupportedLanguages; } } /// <summary> @@ -164,9 +373,60 @@ namespace MonoDevelop.Projects /// </param> public virtual string GetDefaultBuildAction (string fileName) { - return IsCompileable (fileName) ? BuildAction.Compile : BuildAction.None; + return ProjectExtension.OnGetDefaultBuildAction (fileName); } - + + public string GetDefaultResourceId (ProjectFile projectFile) + { + return ProjectExtension.OnGetDefaultResourceId (projectFile); + } + + protected virtual string OnGetDefaultResourceId (ProjectFile projectFile) + { + return MSBuildResourceHandler.Instance.GetDefaultResourceId (projectFile); + } + + internal ProjectItem CreateProjectItem (IMSBuildItemEvaluated item) + { + return ProjectExtension.OnCreateProjectItem (item); + } + + protected virtual ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item) + { + if (item.Name == "Folder") + return new ProjectFile (); + + // Unknown item. Must be a file. + if (!string.IsNullOrEmpty (item.Include) && !UnsupportedItems.Contains (item.Name) && IsValidFile (item.Include)) + return new ProjectFile (); + + return new UnknownProjectItem (item.Name, item.Include); + } + + bool IsValidFile (string path) + { + // If it is an absolute uri, it's not a valid file + try { + if (Uri.IsWellFormedUriString (path, UriKind.Absolute)) { + var f = new Uri (path); + return f.Scheme == "file"; + } + } catch { + // Old mono versions may crash in IsWellFormedUriString if the path + // is not an uri. + } + return true; + } + + // Items generated by VS but which MD is not using and should be ignored + + internal static readonly IList<string> UnsupportedItems = new string[] { + "BootstrapperFile", "AppDesigner", "WebReferences", "WebReferenceUrl", "Service", + "ProjectReference", "Reference", // Reference elements are included here because they are special-cased for DotNetProject, and they are unsupported in other types of projects + "InternalsVisibleTo", + "InternalsVisibleToTest" + }; + /// <summary> /// Gets a project file. /// </summary> @@ -255,7 +515,7 @@ namespace MonoDevelop.Projects /// </summary> protected virtual IEnumerable<string> GetStandardBuildActions () { - return BuildAction.StandardActions; + return ProjectExtension.OnGetStandardBuildActions (); } /// <summary> @@ -263,25 +523,244 @@ namespace MonoDevelop.Projects /// </summary> protected virtual IList<string> GetCommonBuildActions () { - return BuildAction.StandardActions; + return ProjectExtension.OnGetCommonBuildActions (); } - public static Project LoadProject (string filename, IProgressMonitor monitor) + public override void Dispose () { - Project prj = Services.ProjectService.ReadSolutionItem (monitor, filename) as Project; - if (prj == null) - throw new InvalidOperationException ("Invalid project file: " + filename); + FileService.FileChanged -= OnFileChanged; + Runtime.SystemAssemblyService.DefaultRuntimeChanged -= OnDefaultRuntimeChanged; + CleanupProjectBuilder (); + base.Dispose (); + } - return prj; + /// <summary> + /// Runs a build or execution target. + /// </summary> + /// <returns> + /// The result of the operation + /// </returns> + /// <param name='monitor'> + /// A progress monitor + /// </param> + /// <param name='target'> + /// Name of the target + /// </param> + /// <param name='configuration'> + /// Configuration to use to run the target + /// </param> + public Task<BuildResult> RunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration) + { + return ProjectExtension.OnRunTarget (monitor, target, configuration); } + public bool SupportsTarget (string target) + { + return !IsUnsupportedProject && ProjectExtension.OnGetSupportsTarget (target); + } - public override void Dispose () + protected virtual bool OnGetSupportsTarget (string target) { - FileService.FileChanged -= OnFileChanged; - base.Dispose (); + return target == "Build" || target == "Clean"; } - + + /// <summary> + /// Runs a build or execution target. + /// </summary> + /// <returns> + /// The result of the operation + /// </returns> + /// <param name='monitor'> + /// A progress monitor + /// </param> + /// <param name='target'> + /// Name of the target + /// </param> + /// <param name='configuration'> + /// Configuration to use to run the target + /// </param> + /// <remarks> + /// Subclasses can override this method to provide a custom implementation of project operations such as + /// build or clean. The default implementation delegates the execution to the more specific OnBuild + /// and OnClean methods, or to the item handler for other targets. + /// </remarks> + internal async protected virtual Task<BuildResult> OnRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration) + { + if (target == ProjectService.BuildTarget) + return await RunBuildTarget (monitor, configuration); + else if (target == ProjectService.CleanTarget) + return await RunCleanTarget (monitor, configuration); + return await RunMSBuildTarget (monitor, target, configuration) ?? new BuildResult (); + } + + + async Task<BuildResult> DoRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration) + { + if (target == ProjectService.BuildTarget) { + SolutionItemConfiguration conf = GetConfiguration (configuration); + if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Build)) { + if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Build, configuration)) { + var r = new BuildResult (); + r.AddError (GettextCatalog.GetString ("Custom command execution failed")); + return r; + } + return BuildResult.Success; + } + } else if (target == ProjectService.CleanTarget) { + SolutionItemConfiguration config = GetConfiguration (configuration); + if (config != null && config.CustomCommands.HasCommands (CustomCommandType.Clean)) { + if (!await config.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Clean, configuration)) { + var r = new BuildResult (); + r.AddError (GettextCatalog.GetString ("Custom command execution failed")); + return r; + } + return BuildResult.Success; + } + } + return await OnRunTarget (monitor, target, configuration); + } + + async Task<BuildResult> RunMSBuildTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration) + { + if (CheckUseMSBuildEngine (configuration)) { + LogWriter logWriter = new LogWriter (monitor.Log); + RemoteProjectBuilder builder = GetProjectBuilder (); + var configs = GetConfigurations (configuration); + + MSBuildResult result = null; + await Task.Factory.StartNew (delegate { + result = builder.Run (configs, logWriter, MSBuildProjectService.DefaultMSBuildVerbosity, new[] { target }, null, null); + System.Runtime.Remoting.RemotingServices.Disconnect (logWriter); + }); + + var br = new BuildResult (); + foreach (var err in result.Errors) { + FilePath file = null; + if (err.File != null) + file = Path.Combine (Path.GetDirectoryName (err.ProjectFile), err.File); + + if (err.IsWarning) + br.AddWarning (file, err.LineNumber, err.ColumnNumber, err.Code, err.Message); + else + br.AddError (file, err.LineNumber, err.ColumnNumber, err.Code, err.Message); + } + return br; + } + else { + CleanupProjectBuilder (); + if (this is DotNetProject) { + var handler = new MonoDevelop.Projects.Formats.MD1.MD1DotNetProjectHandler ((DotNetProject)this); + return await handler.RunTarget (monitor, target, configuration); + } + } + return null; + } + + internal ProjectConfigurationInfo[] GetConfigurations (ConfigurationSelector configuration) + { + // Returns a list of project/configuration information for the provided item and all its references + List<ProjectConfigurationInfo> configs = new List<ProjectConfigurationInfo> (); + var c = GetConfiguration (configuration); + configs.Add (new ProjectConfigurationInfo () { + ProjectFile = FileName, + Configuration = c.Name, + Platform = GetExplicitPlatform (c) + }); + foreach (var refProject in GetReferencedItems (configuration).OfType<Project> ()) { + var refConfig = refProject.GetConfiguration (configuration); + if (refConfig != null) { + configs.Add (new ProjectConfigurationInfo () { + ProjectFile = refProject.FileName, + Configuration = refConfig.Name, + Platform = GetExplicitPlatform (refConfig) + }); + } + } + return configs.ToArray (); + } + + //for some reason, MD internally handles "AnyCPU" as "", but we need to be explicit when + //passing it to the build engine + static string GetExplicitPlatform (SolutionItemConfiguration configObject) + { + if (string.IsNullOrEmpty (configObject.Platform)) { + return "AnyCPU"; + } + return configObject.Platform; + } + + #region Project builder management + + RemoteProjectBuilder projectBuilder; + string lastBuildToolsVersion; + string lastBuildRuntime; + string lastFileName; + string lastSlnFileName; + object builderLock = new object (); + + internal RemoteProjectBuilder GetProjectBuilder () + { + //FIXME: we can't really have per-project runtimes, has to be per-solution + TargetRuntime runtime = null; + var ap = this as IAssemblyProject; + runtime = ap != null ? ap.TargetRuntime : Runtime.SystemAssemblyService.CurrentRuntime; + + var sln = ParentSolution; + var slnFile = sln != null ? sln.FileName : null; + + lock (builderLock) { + if (projectBuilder == null || lastBuildToolsVersion != ToolsVersion || lastBuildRuntime != runtime.Id || lastFileName != FileName || lastSlnFileName != slnFile) { + if (projectBuilder != null) { + projectBuilder.Dispose (); + projectBuilder = null; + } + projectBuilder = MSBuildProjectService.GetProjectBuilder (runtime, ToolsVersion, FileName, slnFile); + projectBuilder.Disconnected += delegate { + CleanupProjectBuilder (); + }; + lastBuildToolsVersion = ToolsVersion; + lastBuildRuntime = runtime.Id; + lastFileName = FileName; + lastSlnFileName = slnFile; + } else if (modifiedInMemory) { + modifiedInMemory = false; + // TODO NPM +// var p = SaveProject (new NullProgressMonitor ()); +// projectBuilder.RefreshWithContent (p.SaveToString ()); + } + } + return projectBuilder; + } + + void CleanupProjectBuilder () + { + if (projectBuilder != null) { + projectBuilder.Dispose (); + projectBuilder = null; + } + } + + #endregion + + /// <summary>Whether to use the MSBuild engine for the specified item.</summary> + internal bool CheckUseMSBuildEngine (ConfigurationSelector sel, bool checkReferences = true) + { + // if the item mandates MSBuild, always use it + if (RequireMSBuildEngine) + return true; + // if the user has set the option, use the setting + if (UseMSBuildEngine.HasValue) + return UseMSBuildEngine.Value; + + // If the item type defaults to using MSBuild, only use MSBuild if its direct references also use MSBuild. + // This prevents a not-uncommon common error referencing non-MSBuild projects from MSBuild projects + // NOTE: This adds about 11ms to the load/build/etc times of the MonoDevelop solution. Doing it recursively + // adds well over a second. + return UseMSBuildEngineByDefault && ( + !checkReferences || GetReferencedItems (sel).OfType<Project>().All (i => i.CheckUseMSBuildEngine (sel, false)) + ); + } + /// <summary> /// Adds a file to the project /// </summary> @@ -394,11 +873,15 @@ namespace MonoDevelop.Projects //so in order to avoid doing them twice when using the msbuild engine, we special-case them bool UsingMSBuildEngine (ConfigurationSelector sel) { - var msbuildHandler = ItemHandler as MonoDevelop.Projects.Formats.MSBuild.MSBuildProjectHandler; - return msbuildHandler != null && msbuildHandler.UseMSBuildEngineForItem (this, sel); + return CheckUseMSBuildEngine (sel); } - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return RunTarget (monitor, "Build", configuration); + } + + async Task<BuildResult> RunBuildTarget (ProgressMonitor monitor, ConfigurationSelector configuration) { // create output directory, if not exists ProjectConfiguration conf = GetConfiguration (configuration) as ProjectConfiguration; @@ -411,7 +894,7 @@ namespace MonoDevelop.Projects StringParserService.Properties["Project"] = Name; if (UsingMSBuildEngine (configuration)) { - return DoBuild (monitor, configuration); + return await DoBuild (monitor, configuration); } string outputDir = conf.OutputDirectory; @@ -429,7 +912,7 @@ namespace MonoDevelop.Projects monitor.Log.WriteLine ("Performing main compilation..."); - BuildResult res = DoBuild (monitor, configuration); + BuildResult res = await DoBuild (monitor, configuration); if (res != null) { string errorString = GettextCatalog.GetPluralString ("{0} error", "{0} errors", res.ErrorCount, res.ErrorCount); @@ -454,7 +937,7 @@ namespace MonoDevelop.Projects /// Copies all support files to the output directory of the given configuration. Support files /// include: assembly references with the Local Copy flag, data files with the Copy to Output option, etc. /// </remarks> - public void CopySupportFiles (IProgressMonitor monitor, ConfigurationSelector configuration) + public void CopySupportFiles (ProgressMonitor monitor, ConfigurationSelector configuration) { ProjectConfiguration config = (ProjectConfiguration) GetConfiguration (configuration); @@ -505,7 +988,7 @@ namespace MonoDevelop.Projects /// Deletes all support files from the output directory of the given configuration. Support files /// include: assembly references with the Local Copy flag, data files with the Copy to Output option, etc. /// </remarks> - public void DeleteSupportFiles (IProgressMonitor monitor, ConfigurationSelector configuration) + public async Task DeleteSupportFiles (ProgressMonitor monitor, ConfigurationSelector configuration) { ProjectConfiguration config = (ProjectConfiguration) GetConfiguration (configuration); @@ -517,7 +1000,7 @@ namespace MonoDevelop.Projects continue; try { - dest.Delete (); + await dest.DeleteAsync (); } catch (IOException ex) { monitor.ReportError (GettextCatalog.GetString ("Error deleting support file '{0}'.", dest), ex); } @@ -559,13 +1042,17 @@ namespace MonoDevelop.Projects /// </remarks> internal protected virtual void PopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) { + ProjectExtension.OnPopulateSupportFileList (list, configuration); + } + void DoPopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) + { foreach (ProjectFile pf in Files) { if (pf.CopyToOutputDirectory == FileCopyMode.None) continue; list.Add (pf.FilePath, pf.CopyToOutputDirectory == FileCopyMode.PreserveNewest, pf.ProjectVirtualPath); } } - + /// <summary> /// Gets a list of files generated when building this project /// </summary> @@ -601,6 +1088,10 @@ namespace MonoDevelop.Projects /// </remarks> internal protected virtual void PopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration) { + ProjectExtension.OnPopulateOutputFileList (list, configuration); + } + void DoPopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration) + { string file = GetOutputFileName (configuration); if (file != null) list.Add (file); @@ -622,55 +1113,64 @@ namespace MonoDevelop.Projects /// This method is invoked to build the project. Support files such as files with the Copy to Output flag will /// be copied before calling this method. /// </remarks> - protected virtual BuildResult DoBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected async virtual Task<BuildResult> DoBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { - BuildResult res = ItemHandler.RunTarget (monitor, "Build", configuration); + BuildResult res = await RunMSBuildTarget (monitor, "Build", configuration); return res ?? new BuildResult (); } - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return RunTarget (monitor, "Clean", configuration); + } + + async Task<BuildResult> RunCleanTarget (ProgressMonitor monitor, ConfigurationSelector configuration) { ProjectConfiguration config = GetConfiguration (configuration) as ProjectConfiguration; if (config == null) { monitor.ReportError (GettextCatalog.GetString ("Configuration '{0}' not found in project '{1}'", configuration, Name), null); - return; + return BuildResult.Success; } if (UsingMSBuildEngine (configuration)) { - DoClean (monitor, config.Selector); - return; + return await DoClean (monitor, config.Selector); } monitor.Log.WriteLine ("Removing output files..."); - - // Delete generated files - foreach (FilePath file in GetOutputFiles (configuration)) { - if (File.Exists (file)) { - file.Delete (); - if (file.ParentDirectory.CanonicalPath != config.OutputDirectory.CanonicalPath && Directory.GetFiles (file.ParentDirectory).Length == 0) - file.ParentDirectory.Delete (); + + var filesToDelete = GetOutputFiles (configuration).ToArray (); + + await Task.Factory.StartNew (delegate { + // Delete generated files + foreach (FilePath file in filesToDelete) { + if (File.Exists (file)) { + file.Delete (); + if (file.ParentDirectory.CanonicalPath != config.OutputDirectory.CanonicalPath && Directory.GetFiles (file.ParentDirectory).Length == 0) + file.ParentDirectory.Delete (); + } } - } + }); - DeleteSupportFiles (monitor, configuration); + await DeleteSupportFiles (monitor, configuration); - DoClean (monitor, config.Selector); + var res = await DoClean (monitor, config.Selector); monitor.Log.WriteLine (GettextCatalog.GetString ("Clean complete")); + return res; } - protected virtual void DoClean (IProgressMonitor monitor, ConfigurationSelector configuration) + protected virtual Task<BuildResult> DoClean (ProgressMonitor monitor, ConfigurationSelector configuration) { - ItemHandler.RunTarget (monitor, "Clean", configuration); + return RunMSBuildTarget (monitor, "Clean", configuration); } - protected internal override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + protected async override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { ProjectConfiguration config = GetConfiguration (configuration) as ProjectConfiguration; if (config == null) { monitor.ReportError (GettextCatalog.GetString ("Configuration '{0}' not found in project '{1}'", configuration, Name), null); return; } - DoExecute (monitor, context, configuration); + await DoExecute (monitor, context, configuration); } /// <summary> @@ -685,8 +1185,9 @@ namespace MonoDevelop.Projects /// <param name='configuration'> /// Configuration to execute. /// </param> - protected virtual void DoExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + protected virtual Task DoExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { + return new Task (delegate {}); } /// <summary> @@ -700,14 +1201,21 @@ namespace MonoDevelop.Projects /// </param> public virtual FilePath GetOutputFileName (ConfigurationSelector configuration) { - return FilePath.Null; + return ProjectExtension.OnGetOutputFileName (configuration); } - protected internal override bool OnGetNeedsBuilding (ConfigurationSelector configuration) + internal protected override bool OnGetNeedsBuilding (ConfigurationSelector configuration) { return CheckNeedsBuild (configuration); } + protected override void OnSetNeedsBuilding (ConfigurationSelector configuration) + { + var of = GetOutputFileName (configuration); + if (File.Exists (of)) + File.Delete (of); + } + /// <summary> /// Checks if the project needs to be built /// </summary> @@ -734,7 +1242,7 @@ namespace MonoDevelop.Projects } } - foreach (SolutionItem pref in GetReferencedItems (configuration)) { + foreach (SolutionFolderItem pref in GetReferencedItems (configuration)) { if (pref.GetLastBuildTime (configuration) > tim) return true; } @@ -778,16 +1286,19 @@ namespace MonoDevelop.Projects } } - protected internal override List<FilePath> OnGetItemFiles (bool includeReferencedFiles) + protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) { - List<FilePath> col = base.OnGetItemFiles (includeReferencedFiles); + var baseFiles = base.OnGetItemFiles (includeReferencedFiles); + if (includeReferencedFiles) { + List<FilePath> col = new List<FilePath> (); foreach (ProjectFile pf in Files) { if (pf.Subtype != Subtype.Directory) col.Add (pf.FilePath); } + baseFiles = baseFiles.Concat (col); } - return col; + return baseFiles; } protected internal override void OnItemsAdded (IEnumerable<ProjectItem> objs) @@ -908,6 +1419,775 @@ namespace MonoDevelop.Projects } } + internal void ReadProject (ProgressMonitor monitor, MSBuildProject msproject) + { + OnReadProjectHeader (monitor, msproject); + ProjectExtension.OnReadProject (monitor, msproject); + NeedsReload = false; + } + + bool newProject; + + internal MSBuildProject WriteProject (ProgressMonitor monitor) + { + MSBuildProject msproject = new MSBuildProject (); + newProject = FileName == null || !File.Exists (FileName); + if (newProject) { + if (SupportsBuild ()) + msproject.DefaultTargets = "Build"; + msproject.FileName = FileName; + } else { + msproject.Load (FileName); + } + + OnWriteProjectHeader (monitor, msproject); + ProjectExtension.OnWriteProject (monitor, msproject); + + return msproject; + } + + class ConfigData + { + public ConfigData (string conf, string plt, IMSBuildPropertySet grp) + { + Config = conf; + Platform = plt; + Group = grp; + } + + public bool FullySpecified { + get { return Config != Unspecified && Platform != Unspecified; } + } + + public string Config; + public string Platform; + public IMSBuildPropertySet Group; + public bool Exists; + public bool IsNew; // The group did not exist in the original file + } + + const string Unspecified = null; + ITimeTracker timer; + + protected virtual void OnReadProjectHeader (ProgressMonitor monitor, MSBuildProject msproject) + { + timer = Counters.ReadMSBuildProject.BeginTiming (); + + ToolsVersion = msproject.ToolsVersion; + if (string.IsNullOrEmpty (ToolsVersion)) + ToolsVersion = "2.0"; + + IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup (); + // Avoid crash if there is not global group + if (globalGroup == null) + globalGroup = msproject.AddNewPropertyGroup (false); + + productVersion = globalGroup.GetValue ("ProductVersion"); + schemaVersion = globalGroup.GetValue ("SchemaVersion"); + + // Get the project ID + + string itemGuid = globalGroup.GetValue ("ProjectGuid"); + if (itemGuid == null) + throw new UserException ("Project file doesn't have a valid ProjectGuid"); + + // Workaround for a VS issue. VS doesn't include the curly braces in the ProjectGuid + // of shared projects. + if (!itemGuid.StartsWith ("{", StringComparison.Ordinal)) + itemGuid = "{" + itemGuid + "}"; + + ItemId = itemGuid.ToUpper (); + + // Get the project GUIDs + + string projectTypeGuids = globalGroup.GetValue ("ProjectTypeGuids"); + + var subtypeGuids = new List<string> (); + if (projectTypeGuids != null) { + foreach (string guid in projectTypeGuids.Split (';')) { + string sguid = guid.Trim (); + if (sguid.Length > 0 && string.Compare (sguid, TypeGuid, StringComparison.OrdinalIgnoreCase) != 0) + subtypeGuids.Add (guid); + } + } + flavorGuids = subtypeGuids.ToArray (); + + if (!CheckAllFlavorsSupported ()) { + var guids = new [] { TypeGuid }; + var projectInfo = MSBuildProjectService.GetUnknownProjectTypeInfo (guids.Concat (flavorGuids).ToArray (), FileName); + IsUnsupportedProject = true; + if (projectInfo != null) + UnsupportedProjectMessage = projectInfo.GetInstructions (); + } + + // Common properties + + Description = msproject.EvaluatedProperties.GetValue ("Description", ""); + baseIntermediateOutputPath = msproject.EvaluatedProperties.GetPathValue ("BaseIntermediateOutputPath", defaultValue:BaseDirectory.Combine ("obj"), relativeToProject:true); + + RemoveDuplicateItems (msproject); + } + + protected virtual void OnReadProject (ProgressMonitor monitor, MSBuildProject msproject) + { + timer.Trace ("Read project items"); + LoadProjectItems (msproject, ProjectItemFlags.None); + + timer.Trace ("Read configurations"); + + List<ConfigData> configData = GetConfigData (msproject, false); + List<ConfigData> partialConfigurations = new List<ConfigData> (); + HashSet<string> handledConfigurations = new HashSet<string> (); + var configurations = new HashSet<string> (); + var platforms = new HashSet<string> (); + + IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup (); + configData.Insert (0, new ConfigData (Unspecified, Unspecified, globalGroup)); + + // Load configurations, skipping the dummy config at index 0. + for (int i = 1; i < configData.Count; i++) { + ConfigData cgrp = configData[i]; + string platform = cgrp.Platform; + string conf = cgrp.Config; + + if (platform != Unspecified) + platforms.Add (platform); + + if (conf != Unspecified) + configurations.Add (conf); + + if (conf == Unspecified || platform == Unspecified) { + // skip partial configurations for now... + partialConfigurations.Add (cgrp); + continue; + } + + string key = conf + "|" + platform; + if (handledConfigurations.Contains (key)) + continue; + + LoadConfiguration (monitor, configData, conf, platform); + + handledConfigurations.Add (key); + } + + // Now we can load any partial configurations by combining them with known configs or platforms. + if (partialConfigurations.Count > 0) { + if (platforms.Count == 0) + platforms.Add (string.Empty); // AnyCpu + + foreach (ConfigData cgrp in partialConfigurations) { + if (cgrp.Config != Unspecified && cgrp.Platform == Unspecified) { + string conf = cgrp.Config; + + foreach (var platform in platforms) { + string key = conf + "|" + platform; + + if (handledConfigurations.Contains (key)) + continue; + + LoadConfiguration (monitor, configData, conf, platform); + + handledConfigurations.Add (key); + } + } else if (cgrp.Config == Unspecified && cgrp.Platform != Unspecified) { + string platform = cgrp.Platform; + + foreach (var conf in configurations) { + string key = conf + "|" + platform; + + if (handledConfigurations.Contains (key)) + continue; + + LoadConfiguration (monitor, configData, conf, platform); + + handledConfigurations.Add (key); + } + } + } + } + + // Read extended properties + + timer.Trace ("Read extended properties"); + } + + List<ConfigData> GetConfigData (MSBuildProject msproject, bool includeGlobalGroups) + { + List<ConfigData> configData = new List<ConfigData> (); + foreach (MSBuildPropertyGroup cgrp in msproject.PropertyGroups) { + string conf, platform; + if (ParseConfigCondition (cgrp.Condition, out conf, out platform) || includeGlobalGroups) + configData.Add (new ConfigData (conf, platform, cgrp)); + } + return configData; + } + + bool ParseConfigCondition (string cond, out string config, out string platform) + { + config = platform = Unspecified; + int i = cond.IndexOf ("==", StringComparison.Ordinal); + if (i == -1) + return false; + if (cond.Substring (0, i).Trim () == "'$(Configuration)|$(Platform)'") { + if (!ExtractConfigName (cond.Substring (i + 2), out cond)) + return false; + i = cond.IndexOf ('|'); + if (i != -1) { + config = cond.Substring (0, i); + platform = cond.Substring (i+1); + } else { + // Invalid configuration + return false; + } + if (platform == "AnyCPU") + platform = string.Empty; + return true; + } + else if (cond.Substring (0, i).Trim () == "'$(Configuration)'") { + if (!ExtractConfigName (cond.Substring (i + 2), out config)) + return false; + platform = Unspecified; + return true; + } + else if (cond.Substring (0, i).Trim () == "'$(Platform)'") { + config = Unspecified; + if (!ExtractConfigName (cond.Substring (i + 2), out platform)) + return false; + if (platform == "AnyCPU") + platform = string.Empty; + return true; + } + return false; + } + + bool ExtractConfigName (string name, out string config) + { + config = name.Trim (' '); + if (config.Length <= 2) + return false; + if (config [0] != '\'' || config [config.Length - 1] != '\'') + return false; + config = config.Substring (1, config.Length - 2); + return config.IndexOf ('\'') == -1; + } + + void LoadConfiguration (ProgressMonitor monitor, List<ConfigData> configData, string conf, string platform) + { + IMSBuildPropertySet grp = GetMergedConfiguration (configData, conf, platform, null); + ProjectConfiguration config = (ProjectConfiguration) CreateConfiguration (conf); + + config.Platform = platform; + projectExtension.OnReadConfiguration (monitor, config, grp); + Configurations.Add (config); + } + + protected virtual void OnReadConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet grp) + { + config.Read (grp, GetToolsFormat ()); + } + + void RemoveDuplicateItems (MSBuildProject msproject) + { + timer.Trace ("Checking for duplicate items"); + + var uniqueIncludes = new Dictionary<string,object> (); + var toRemove = new List<MSBuildItem> (); + foreach (MSBuildItem bi in msproject.GetAllItems ()) { + object existing; + string key = bi.Name + "<" + bi.Include; + if (!uniqueIncludes.TryGetValue (key, out existing)) { + uniqueIncludes[key] = bi; + continue; + } + var exBi = existing as MSBuildItem; + if (exBi != null) { + if (exBi.Condition != bi.Condition || exBi.Element.InnerXml != bi.Element.InnerXml) { + uniqueIncludes[key] = new List<MSBuildItem> { exBi, bi }; + } else { + toRemove.Add (bi); + } + continue; + } + + var exList = (List<MSBuildItem>)existing; + bool found = false; + foreach (var m in (exList)) { + if (m.Condition == bi.Condition && m.Element.InnerXml == bi.Element.InnerXml) { + found = true; + break; + } + } + if (!found) { + exList.Add (bi); + } else { + toRemove.Add (bi); + } + } + if (toRemove.Count == 0) + return; + + timer.Trace ("Removing duplicate items"); + + foreach (var t in toRemove) + msproject.RemoveItem (t); + } + + IMSBuildPropertySet GetMergedConfiguration (List<ConfigData> configData, string conf, string platform, IMSBuildPropertySet propGroupLimit) + { + IMSBuildPropertySet merged = null; + + foreach (ConfigData grp in configData) { + if (grp.Group == propGroupLimit) + break; + if ((grp.Config == conf || grp.Config == Unspecified || conf == Unspecified) && (grp.Platform == platform || grp.Platform == Unspecified || platform == Unspecified)) { + if (merged == null) + merged = grp.Group; + else if (merged is MSBuildPropertyGroupMerged) + ((MSBuildPropertyGroupMerged)merged).Add (grp.Group); + else { + MSBuildPropertyGroupMerged m = new MSBuildPropertyGroupMerged (merged.Project, GetToolsFormat()); + m.Add (merged); + m.Add (grp.Group); + merged = m; + } + } + } + return merged; + } + + //HACK: the solution's format is irrelevant to MSBuild projects, what matters is the ToolsVersion + // but other parts of the MD API expect a FileFormat + internal MSBuildFileFormat GetToolsFormat () + { + switch (ToolsVersion) { + case "2.0": + return new MSBuildFileFormatVS05 (); + case "3.5": + return new MSBuildFileFormatVS08 (); + case "4.0": + if (SolutionFormat != null && SolutionFormat.Id == "MSBuild10") + return SolutionFormat; + return new MSBuildFileFormatVS12 (); + case "12.0": + return new MSBuildFileFormatVS12 (); + default: + throw new Exception ("Unknown ToolsVersion '" + ToolsVersion + "'"); + } + } + + internal void LoadProjectItems (MSBuildProject msproject, ProjectItemFlags flags) + { + foreach (var buildItem in msproject.GetAllItems ()) { + ProjectItem it = ReadItem (buildItem); + if (it == null) + continue; + it.Flags = flags; + if (it is ProjectFile) { + var file = (ProjectFile)it; + if (file.Name.IndexOf ('*') > -1) { + // Thanks to IsOriginatedFromWildcard, these expanded items will not be saved back to disk. + foreach (var expandedItem in ResolveWildcardItems (file)) + Items.Add (expandedItem); + // Add to wildcard items (so it can be re-saved) instead of Items (where tools will + // try to compile and display these nonstandard items + WildcardItems.Add (it); + continue; + } + } + Items.Add (it); + } + } + + internal override void SetSolutionFormat (MSBuildFileFormat format, bool converting) + { + base.SetSolutionFormat (format, converting); + + // when converting formats, set ToolsVersion, ProductVersion, SchemaVersion to default values written by VS + // this happens on creation too + // else we leave them alone and just roundtrip them + if (converting) { + ToolsVersion = format.DefaultToolsVersion; + productVersion = format.DefaultProductVersion; + schemaVersion = format.DefaultSchemaVersion; + } + } + + internal ProjectItem ReadItem (IMSBuildItemEvaluated buildItem) + { + var item = CreateProjectItem (buildItem); + item.Read (this, buildItem); + return item; + } + + const string RecursiveDirectoryWildcard = "**"; + static readonly char[] directorySeparators = new [] { + Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar + }; + + static string GetWildcardDirectoryName (string path) + { + int indexOfLast = path.LastIndexOfAny (directorySeparators); + if (indexOfLast < 0) + return String.Empty; + return path.Substring (0, indexOfLast); + } + + static string GetWildcardFileName (string path) + { + int indexOfLast = path.LastIndexOfAny (directorySeparators); + if (indexOfLast < 0) + return path; + if (indexOfLast == path.Length) + return String.Empty; + return path.Substring (indexOfLast + 1, path.Length - (indexOfLast + 1)); + } + + + static IEnumerable<string> ExpandWildcardFilePath (string filePath) + { + if (String.IsNullOrWhiteSpace (filePath)) + throw new ArgumentException ("Not a wildcard path"); + + string dir = GetWildcardDirectoryName (filePath); + string file = GetWildcardFileName (filePath); + + if (String.IsNullOrEmpty (dir) || String.IsNullOrEmpty (file)) + return null; + + SearchOption searchOption = SearchOption.TopDirectoryOnly; + if (dir.EndsWith (RecursiveDirectoryWildcard, StringComparison.Ordinal)) { + dir = dir.Substring (0, dir.Length - RecursiveDirectoryWildcard.Length); + searchOption = SearchOption.AllDirectories; + } + + if (!Directory.Exists (dir)) + return null; + + return Directory.GetFiles (dir, file, searchOption); + } + + static IEnumerable<ProjectFile> ResolveWildcardItems (ProjectFile wildcardFile) + { + var paths = ExpandWildcardFilePath (wildcardFile.Name); + if (paths == null) + yield break; + foreach (var resolvedFilePath in paths) { + var projectFile = (ProjectFile)wildcardFile.Clone (); + projectFile.Name = resolvedFilePath; + projectFile.Flags |= ProjectItemFlags.DontPersist; + yield return projectFile; + } + } + + struct MergedPropertyValue + { + public readonly string XmlValue; + public readonly bool PreserveExistingCase; + public readonly bool IsDefault; + + public MergedPropertyValue (string xmlValue, bool preserveExistingCase, bool isDefault) + { + this.XmlValue = xmlValue; + this.PreserveExistingCase = preserveExistingCase; + this.IsDefault = isDefault; + } + } + + protected virtual void OnWriteProjectHeader (ProgressMonitor monitor, MSBuildProject msproject) + { + IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup (); + if (globalGroup == null) + globalGroup = msproject.AddNewPropertyGroup (false); + + if (Configurations.Count > 0) { + ItemConfiguration conf = Configurations.FirstOrDefault<ItemConfiguration> (c => c.Name == "Debug"); + if (conf == null) conf = Configurations [0]; + globalGroup.SetValue ("Configuration", conf.Name, condition:" '$(Configuration)' == '' "); + + string platform = conf.Platform.Length == 0 ? "AnyCPU" : conf.Platform; + globalGroup.SetValue ("Platform", platform, condition:" '$(Platform)' == '' "); + } + + if (TypeGuid == MSBuildProjectService.GenericItemGuid) { + DataType dt = MSBuildProjectService.DataContext.GetConfigurationDataType (GetType ()); + globalGroup.SetValue ("ItemType", dt.Name); + } + + globalGroup.SetValue ("ProductVersion", productVersion); + globalGroup.SetValue ("SchemaVersion", schemaVersion); + + globalGroup.SetValue ("ProjectGuid", ItemId); + + if (flavorGuids.Length > 0) { + string gg = string.Join (";", flavorGuids); + gg += ";" + TypeGuid; + globalGroup.SetValue ("ProjectTypeGuids", gg.ToUpper (), preserveExistingCase:true); + } else { + globalGroup.RemoveProperty ("ProjectTypeGuids"); + } + + // having no ToolsVersion is equivalent to 2.0, roundtrip that correctly + if (ToolsVersion != "2.0") + msproject.ToolsVersion = ToolsVersion; + else if (string.IsNullOrEmpty (msproject.ToolsVersion)) + msproject.ToolsVersion = null; + else + msproject.ToolsVersion = "2.0"; + + msproject.GetGlobalPropertyGroup ().SetValue ("Description", Description, ""); + msproject.GetGlobalPropertyGroup ().SetValue ("BaseIntermediateOutputPath", BaseIntermediateOutputPath, defaultValue:BaseDirectory.Combine ("obj"), relativeToProject:true); + } + + protected virtual void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject) + { + var toolsFormat = GetToolsFormat (); + + IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup (); + + // Configurations + + if (Configurations.Count > 0) { + List<ConfigData> configData = GetConfigData (msproject, true); + + // Write configuration data, creating new property groups if necessary + + foreach (ProjectConfiguration conf in Configurations) { + ConfigData cdata = FindPropertyGroup (configData, conf); + if (cdata == null) { + MSBuildPropertyGroup pg = msproject.AddNewPropertyGroup (true); + pg.IgnoreDefaultValues = true; + pg.Condition = BuildConfigCondition (conf.Name, conf.Platform); + cdata = new ConfigData (conf.Name, conf.Platform, pg); + cdata.IsNew = true; + configData.Add (cdata); + } + ((MSBuildPropertyGroup)cdata.Group).IgnoreDefaultValues = true; + cdata.Exists = true; + ProjectExtension.OnWriteConfiguration (monitor, conf, cdata.Group); + } + + // Find the properties in all configurations that have the MergeToProject flag set + var mergeToProjectProperties = new HashSet<MergedProperty> (GetMergeToProjectProperties (configData)); + var mergeToProjectPropertyNames = new HashSet<string> (mergeToProjectProperties.Select (p => p.Name)); + var mergeToProjectPropertyValues = new Dictionary<string,MergedPropertyValue> (); + + foreach (ProjectConfiguration conf in Configurations) { + ConfigData cdata = FindPropertyGroup (configData, conf); + var propGroup = (MSBuildPropertyGroup) cdata.Group; + + IMSBuildPropertySet baseGroup = GetMergedConfiguration (configData, conf.Name, conf.Platform, propGroup); + + CollectMergetoprojectProperties (propGroup, mergeToProjectProperties, mergeToProjectPropertyValues); + + propGroup.UnMerge (baseGroup, mergeToProjectPropertyNames); + propGroup.IgnoreDefaultValues = false; + } + + // Move properties with common values from configurations to the main + // property group + foreach (KeyValuePair<string,MergedPropertyValue> prop in mergeToProjectPropertyValues) { + if (!prop.Value.IsDefault) + globalGroup.SetValue (prop.Key, prop.Value.XmlValue, preserveExistingCase: prop.Value.PreserveExistingCase); + else + globalGroup.RemoveProperty (prop.Key); + } + foreach (string prop in mergeToProjectPropertyNames) { + if (!mergeToProjectPropertyValues.ContainsKey (prop)) + globalGroup.RemoveProperty (prop); + } + foreach (SolutionItemConfiguration conf in Configurations) { + var propGroup = FindPropertyGroup (configData, conf).Group; + foreach (string mp in mergeToProjectPropertyValues.Keys) + propGroup.RemoveProperty (mp); + } + + // Remove groups corresponding to configurations that have been removed + // or groups which don't have any property and did not already exist + foreach (ConfigData cd in configData) { + if ((!cd.Exists && cd.FullySpecified) || (cd.IsNew && !cd.Group.Properties.Any ())) + msproject.RemoveGroup ((MSBuildPropertyGroup)cd.Group); + } + } + SaveProjectItems (monitor, toolsFormat, msproject); + + if (msproject.IsNewProject) { + foreach (var im in DefaultImports) + msproject.AddNewImport (im); + } + + foreach (var im in importsAdded) { + if (msproject.GetImport (im.Name, im.Condition) == null) + msproject.AddNewImport (im.Name, im.Condition); + } + foreach (var im in importsRemoved) { + var i = msproject.GetImport (im.Name, im.Condition); + if (i != null) + msproject.RemoveImport (i); + } + } + + void WriteConfiguration (ProgressMonitor monitor, List<ConfigData> configData, string conf, string platform) + { + IMSBuildPropertySet grp = GetMergedConfiguration (configData, conf, platform, null); + ProjectConfiguration config = (ProjectConfiguration) CreateConfiguration (conf); + + config.Platform = platform; + config.Read (grp, GetToolsFormat ()); + Configurations.Add (config); + projectExtension.OnReadConfiguration (monitor, config, grp); + } + + protected virtual void OnWriteConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet pset) + { + config.Write (pset, SolutionFormat); + } + + IEnumerable<MergedProperty> GetMergeToProjectProperties (List<ConfigData> configData) + { + Dictionary<string,MergedProperty> mergeProps = new Dictionary<string, MergedProperty> (); + foreach (var cd in configData.Where (d => d.FullySpecified)) { + foreach (var prop in cd.Group.Properties) { + if (!prop.MergeToMainGroup) { + mergeProps [prop.Name] = null; + } else if (!mergeProps.ContainsKey (prop.Name)) + mergeProps [prop.Name] = prop.CreateMergedProperty (); + } + } + return mergeProps.Values.Where (p => p != null); + } + + void CollectMergetoprojectProperties (IMSBuildPropertySet pgroup, HashSet<MergedProperty> properties, Dictionary<string,MergedPropertyValue> mergeToProjectProperties) + { + // This method checks every property in pgroup which has the MergeToProject flag. + // If the value of this property is the same as the one stored in mergeToProjectProperties + // it means that the property can be merged to the main project property group (so far). + + foreach (var pinfo in new List<MergedProperty> (properties)) { + MSBuildProperty prop = pgroup.GetProperty (pinfo.Name); + + MergedPropertyValue mvalue; + if (!mergeToProjectProperties.TryGetValue (pinfo.Name, out mvalue)) { + if (prop != null) { + // This is the first time the value is checked. Just assign it. + mergeToProjectProperties.Add (pinfo.Name, new MergedPropertyValue (prop.Value, pinfo.PreserveExistingCase, pinfo.IsDefault)); + continue; + } + // If there is no value, it can't be merged + } + else if (prop != null && string.Equals (prop.Value, mvalue.XmlValue, mvalue.PreserveExistingCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + // Same value. It can be merged. + continue; + + // The property can't be merged because different configurations have different + // values for it. Remove it from the list. + properties.Remove (pinfo); + mergeToProjectProperties.Remove (pinfo.Name); + } + } + + struct ItemInfo { + public MSBuildItem Item; + public bool Added; + } + + internal void SaveProjectItems (ProgressMonitor monitor, MSBuildFileFormat toolsFormat, MSBuildProject msproject, string pathPrefix = null) + { + // Remove old items + Dictionary<string, ItemInfo> oldItems = new Dictionary<string, ItemInfo> (); + foreach (MSBuildItem item in msproject.GetAllItems ()) + oldItems [item.Name + "<" + item.UnevaluatedInclude + "<" + item.Condition] = new ItemInfo () { + Item = item + }; + // Add the new items + foreach (ProjectItem ob in Items.Concat (WildcardItems).Where (it => !it.Flags.HasFlag (ProjectItemFlags.DontPersist))) + SaveProjectItem (monitor, toolsFormat, msproject, ob, oldItems, pathPrefix); + foreach (ItemInfo itemInfo in oldItems.Values) { + if (!itemInfo.Added) + msproject.RemoveItem (itemInfo.Item); + } + } + + void SaveProjectItem (ProgressMonitor monitor, MSBuildFileFormat fmt, MSBuildProject msproject, ProjectItem item, Dictionary<string,ItemInfo> oldItems, string pathPrefix = null) + { + var include = item.UnevaluatedInclude ?? item.Include; + if (pathPrefix != null && !include.StartsWith (pathPrefix)) + include = pathPrefix + include; + + MSBuildItem buildItem = AddOrGetBuildItem (msproject, oldItems, item.ItemName, include, item.Condition); + item.Write (fmt, buildItem); + if (pathPrefix != null) + buildItem.Include = include; + } + + MSBuildItem AddOrGetBuildItem (MSBuildProject msproject, Dictionary<string,ItemInfo> oldItems, string name, string include, string condition) + { + ItemInfo itemInfo; + string key = name + "<" + include + "<" + condition; + if (oldItems.TryGetValue (key, out itemInfo)) { + if (!itemInfo.Added) { + itemInfo.Added = true; + oldItems [key] = itemInfo; + } + return itemInfo.Item; + } else { + return msproject.AddNewItem (name, include); + } + } + + ConfigData FindPropertyGroup (List<ConfigData> configData, SolutionItemConfiguration config) + { + foreach (ConfigData data in configData) { + if (data.Config == config.Name && data.Platform == config.Platform) + return data; + } + return null; + } + + string BuildConfigCondition (string config, string platform) + { + if (platform.Length == 0) + platform = "AnyCPU"; + return " '$(Configuration)|$(Platform)' == '" + config + "|" + platform + "' "; + } + + bool IsMergeToProjectProperty (ItemProperty prop) + { + foreach (object at in prop.CustomAttributes) { + if (at is MergeToProjectAttribute) + return true; + } + return false; + } + + public void AddImportIfMissing (string name, string condition) + { + importsAdded.Add (new DotNetProjectImport (name, condition)); + } + + public void RemoveImport (string name) + { + importsRemoved.Add (new DotNetProjectImport (name)); + } + + List <DotNetProjectImport> importsAdded = new List<DotNetProjectImport> (); + + internal IList<DotNetProjectImport> ImportsAdded { + get { return importsAdded; } + } + + List <DotNetProjectImport> importsRemoved = new List<DotNetProjectImport> (); + + internal IList<DotNetProjectImport> ImportsRemoved { + get { return importsRemoved; } + } + + void ImportsSaved () + { + importsAdded.Clear (); + importsRemoved.Clear (); + } internal void NotifyFileRenamedInProject (ProjectFileRenamedEventArgs args) { NotifyModified ("Files"); @@ -919,6 +2199,10 @@ namespace MonoDevelop.Projects /// </summary> protected virtual void OnFileRemovedFromProject (ProjectFileEventArgs e) { + ProjectExtension.OnFileRemovedFromProject (e); + } + void DoOnFileRemovedFromProject (ProjectFileEventArgs e) + { buildActions = null; if (FileRemovedFromProject != null) { FileRemovedFromProject (this, e); @@ -930,38 +2214,54 @@ namespace MonoDevelop.Projects /// </summary> protected virtual void OnFileAddedToProject (ProjectFileEventArgs e) { + ProjectExtension.OnFileAddedToProject (e); + } + void DoOnFileAddedToProject (ProjectFileEventArgs e) + { buildActions = null; if (FileAddedToProject != null) { FileAddedToProject (this, e); } } - + /// <summary> /// Raises the FileChangedInProject event. /// </summary> protected virtual void OnFileChangedInProject (ProjectFileEventArgs e) { + ProjectExtension.OnFileChangedInProject (e); + } + void DoOnFileChangedInProject (ProjectFileEventArgs e) + { if (FileChangedInProject != null) { FileChangedInProject (this, e); } } - + /// <summary> /// Raises the FilePropertyChangedInProject event. /// </summary> protected virtual void OnFilePropertyChangedInProject (ProjectFileEventArgs e) { + ProjectExtension.OnFilePropertyChangedInProject (e); + } + void DoOnFilePropertyChangedInProject (ProjectFileEventArgs e) + { buildActions = null; if (FilePropertyChangedInProject != null) { FilePropertyChangedInProject (this, e); } } - + /// <summary> /// Raises the FileRenamedInProject event. /// </summary> protected virtual void OnFileRenamedInProject (ProjectFileRenamedEventArgs e) { + ProjectExtension.OnFileRenamedInProject (e); + } + void DoOnFileRenamedInProject (ProjectFileRenamedEventArgs e) + { if (FileRenamedInProject != null) { FileRenamedInProject (this, e); } @@ -991,6 +2291,126 @@ namespace MonoDevelop.Projects /// Occurs when a file of this project has been renamed /// </summary> public event ProjectFileRenamedEventHandler FileRenamedInProject; + + + class DefaultMSBuildProjectExtension: ProjectExtension + { + internal protected override bool SupportsFlavor (string guid) + { + return false; + } + + internal protected override bool OnGetIsCompileable (string fileName) + { + return false; + } + + internal protected override void OnGetProjectTypes (HashSet<string> types) + { + Project.OnGetProjectTypes (types); + } + + internal protected override Task<BuildResult> OnRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration) + { + return Project.DoRunTarget (monitor, target, configuration); + } + + internal protected override bool OnGetSupportsTarget (string target) + { + return Project.OnGetSupportsTarget (target); + } + + internal protected override string OnGetDefaultBuildAction (string fileName) + { + return Project.IsCompileable (fileName) ? BuildAction.Compile : BuildAction.None; + } + + internal protected override string OnGetDefaultResourceId (ProjectFile projectFile) + { + return Project.OnGetDefaultResourceId (projectFile); + } + + internal protected override IEnumerable<string> OnGetStandardBuildActions () + { + return BuildAction.StandardActions; + } + + internal protected override IList<string> OnGetCommonBuildActions () + { + return BuildAction.StandardActions; + } + + internal protected override ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item) + { + return Project.OnCreateProjectItem (item); + } + + internal protected override void OnPopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) + { + Project.DoPopulateSupportFileList (list, configuration); + } + + internal protected override void OnPopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration) + { + Project.DoPopulateOutputFileList (list, configuration); + } + + internal protected override FilePath OnGetOutputFileName (ConfigurationSelector configuration) + { + return FilePath.Null; + } + + internal protected override string[] SupportedLanguages { + get { + return new String[] { "" }; + } + } + + internal protected override void OnFileRemovedFromProject (ProjectFileEventArgs e) + { + Project.DoOnFileRemovedFromProject (e); + } + + internal protected override void OnFileAddedToProject (ProjectFileEventArgs e) + { + Project.DoOnFileAddedToProject (e); + } + + internal protected override void OnFileChangedInProject (ProjectFileEventArgs e) + { + Project.DoOnFileChangedInProject (e); + } + + internal protected override void OnFilePropertyChangedInProject (ProjectFileEventArgs e) + { + Project.DoOnFilePropertyChangedInProject (e); + } + + internal protected override void OnFileRenamedInProject (ProjectFileRenamedEventArgs e) + { + Project.DoOnFileRenamedInProject (e); + } + + internal protected override void OnReadProject (ProgressMonitor monitor, MSBuildProject msproject) + { + Project.OnReadProject (monitor, msproject); + } + + internal protected override void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject) + { + Project.OnWriteProject (monitor, msproject); + } + + internal protected override void OnReadConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet grp) + { + Project.OnReadConfiguration (monitor, config, grp); + } + + internal protected override void OnWriteConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet grp) + { + Project.OnWriteConfiguration (monitor, config, grp); + } + } } public delegate void ProjectEventHandler (Object sender, ProjectEventArgs e); diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConfiguration.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConfiguration.cs index 1db4404892..7a4420c57c 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConfiguration.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConfiguration.cs @@ -32,10 +32,12 @@ using System.IO; using MonoDevelop.Core.Serialization; using System.Collections.Generic; using MonoDevelop.Core.StringParsing; +using System.Xml.Linq; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { - public class ProjectConfiguration : SolutionItemConfiguration + public class ProjectConfiguration : SolutionItemConfiguration, IMSBuildDataObject { public ProjectConfiguration () @@ -46,8 +48,64 @@ namespace MonoDevelop.Projects { } - [ProjectPathItemProperty("IntermediateOutputPath")] - private FilePath intermediateOutputDirectory; + #region IProjectConfigurationData implementation + + void IMSBuildDataObject.Read (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + Read (pset, format); + } + + void IMSBuildDataObject.Write (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + Write (pset, format); + } + + #endregion + + internal protected virtual void Read (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + intermediateOutputDirectory = pset.GetPathValue ("IntermediateOutputPath"); + outputDirectory = pset.GetPathValue ("OutputPath", defaultValue:"." + Path.DirectorySeparatorChar); + debugMode = pset.GetValue<bool> ("DebugSymbols"); + pauseConsoleOutput = pset.GetValue ("ConsolePause", true); + externalConsole = pset.GetValue<bool> ("ExternalConsole"); + commandLineParameters = pset.GetValue ("Commandlineparameters", ""); + runWithWarnings = pset.GetValue ("RunWithWarnings", true); + + var svars = pset.GetValue ("EnvironmentVariables"); + if (svars != null) { + XElement vars = XElement.Parse (svars); + foreach (var val in vars.Elements ("Variable")) { + var name = (string)val.Attribute ("name"); + if (name != null) + environmentVariables [name] = (string)val.Attribute ("value"); + } + } + } + + internal protected virtual void Write (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + pset.SetValue ("IntermediateOutputPath", intermediateOutputDirectory, defaultValue:FilePath.Null); + pset.SetValue ("DebugSymbols", debugMode, false); + pset.SetValue ("OutputPath", outputDirectory); + pset.SetValue ("ConsolePause", pauseConsoleOutput, true); + pset.SetValue ("ExternalConsole", externalConsole, false); + pset.SetValue ("Commandlineparameters", commandLineParameters, ""); + pset.SetValue ("RunWithWarnings", runWithWarnings, true); + + if (environmentVariables.Count > 0) { + XElement e = new XElement ("EnvironmentVariables"); + foreach (var v in environmentVariables) { + var val = new XElement ("Variable"); + val.SetAttributeValue ("name", v.Key); + val.SetAttributeValue ("value", v.Value); + e.Add (val); + } + pset.SetValue ("EnvironmentVariables", e.ToString ()); + } + } + + FilePath intermediateOutputDirectory = FilePath.Empty; public virtual FilePath IntermediateOutputDirectory { get { @@ -66,46 +124,37 @@ namespace MonoDevelop.Projects } } - [ProjectPathItemProperty("OutputPath")] - private FilePath outputDirectory = "." + Path.DirectorySeparatorChar; + FilePath outputDirectory = "." + Path.DirectorySeparatorChar; public virtual FilePath OutputDirectory { get { return outputDirectory; } set { outputDirectory = value; } } - [ItemProperty("DebugSymbols", DefaultValue = false)] - private bool debugMode = false; + bool debugMode = false; public bool DebugMode { get { return debugMode; } set { debugMode = value; } } - [ItemProperty("ConsolePause", DefaultValue = true)] - private bool pauseConsoleOutput = true; + bool pauseConsoleOutput = true; public bool PauseConsoleOutput { get { return pauseConsoleOutput; } set { pauseConsoleOutput = value; } } - [ItemProperty("Externalconsole", DefaultValue = false)] - private bool externalConsole = false; + bool externalConsole = false; public bool ExternalConsole { get { return externalConsole; } set { externalConsole = value; } } - [ItemProperty("Commandlineparameters", DefaultValue = "")] - private string commandLineParameters = ""; + string commandLineParameters = ""; public string CommandLineParameters { get { return commandLineParameters; } set { commandLineParameters = value; } } - [ItemProperty("EnvironmentVariables", SkipEmpty = true)] - [ItemProperty("Variable", Scope = "item")] - [ItemProperty("name", Scope = "key")] - [ItemProperty("value", Scope = "value")] - private Dictionary<string, string> environmentVariables = new Dictionary<string, string> (); + Dictionary<string, string> environmentVariables = new Dictionary<string, string> (); public Dictionary<string, string> EnvironmentVariables { get { return environmentVariables; } } @@ -122,8 +171,7 @@ namespace MonoDevelop.Projects return vars; } - [ItemProperty("RunWithWarnings", DefaultValue = true)] - private bool runWithWarnings = true; + bool runWithWarnings = true; public virtual bool RunWithWarnings { get { return runWithWarnings; } set { runWithWarnings = value; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConvertTool.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConvertTool.cs index 6bedef9308..c849d3b8d0 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConvertTool.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectConvertTool.cs @@ -177,7 +177,10 @@ namespace MonoDevelop.Projects destPath = Path.GetDirectoryName (projectFile); destPath = FileService.GetFullPath (destPath); - string ofile = Services.ProjectService.Export (monitor, projectFile, itemsToExport, destPath, format); + var t = Services.ProjectService.Export (monitor, projectFile, itemsToExport, destPath, format); + t.Wait (); + string ofile = t.Result; + if (ofile != null) { Console.WriteLine ("Saved file: " + ofile); return 0; diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectExtension.cs new file mode 100644 index 0000000000..a1dd21715c --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectExtension.cs @@ -0,0 +1,182 @@ +// +// MSBuildProjectExtension.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 System.Collections.Generic; +using MonoDevelop.Core; +using System.Threading.Tasks; +using MonoDevelop.Projects.Formats.MSBuild; +using Mono.Addins; +using System.Linq; + +namespace MonoDevelop.Projects +{ + public class ProjectExtension: SolutionItemExtension + { + ProjectExtension next; + + public Project Project { + get { return (Project) base.Item; } + } + + internal protected override void InitializeChain (ChainedExtension next) + { + base.InitializeChain (next); + this.next = FindNextImplementation<ProjectExtension> (next); + } + + internal protected override bool SupportsObject (WorkspaceObject item) + { + return item is Project && base.SupportsObject (item); + } + + internal protected virtual bool SupportsFlavor (string guid) + { + if (FlavorGuid != null && guid.Equals (FlavorGuid, StringComparison.OrdinalIgnoreCase)) + return true; + return next.SupportsFlavor (guid); + } + + internal protected virtual Task<BuildResult> OnRunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration) + { + return next.OnRunTarget (monitor, target, configuration); + } + + internal protected virtual bool OnGetSupportsTarget (string target) + { + return next.OnGetSupportsTarget (target); + } + + internal protected virtual void OnGetProjectTypes (HashSet<string> types) + { + next.OnGetProjectTypes (types); + } + + internal protected virtual void OnReadProject (ProgressMonitor monitor, MSBuildProject msproject) + { + next.OnReadProject (monitor, msproject); + } + + internal protected virtual void OnReadConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet pset) + { + next.OnReadConfiguration (monitor, config, pset); + } + + internal protected virtual void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject) + { + next.OnWriteProject (monitor, msproject); + } + + internal protected virtual void OnWriteConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet pset) + { + next.OnWriteConfiguration (monitor, config, pset); + } + + #region Building + + internal protected virtual bool OnGetIsCompileable (string fileName) + { + return next.OnGetIsCompileable (fileName); + } + + internal protected virtual string OnGetDefaultBuildAction (string fileName) + { + return next.OnGetDefaultBuildAction (fileName); + } + + internal protected virtual string OnGetDefaultResourceId (ProjectFile projectFile) + { + return next.OnGetDefaultResourceId (projectFile); + } + + internal protected virtual IEnumerable<string> OnGetStandardBuildActions () + { + return next.OnGetStandardBuildActions (); + } + + internal protected virtual IList<string> OnGetCommonBuildActions () + { + return next.OnGetCommonBuildActions (); + } + + internal protected virtual ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item) + { + return next.OnCreateProjectItem (item); + } + + internal protected virtual void OnPopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration) + { + next.OnPopulateSupportFileList (list, configuration); + } + + internal protected virtual void OnPopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration) + { + next.OnPopulateOutputFileList (list, configuration); + } + + internal protected virtual FilePath OnGetOutputFileName (ConfigurationSelector configuration) + { + return next.OnGetOutputFileName (configuration); + } + + internal protected virtual string[] SupportedLanguages { + get { + return next.SupportedLanguages; + } + } + + #endregion + + #region Events + + internal protected virtual void OnFileRemovedFromProject (ProjectFileEventArgs e) + { + next.OnFileRemovedFromProject (e); + } + + internal protected virtual void OnFileAddedToProject (ProjectFileEventArgs e) + { + next.OnFileAddedToProject (e); + } + + internal protected virtual void OnFileChangedInProject (ProjectFileEventArgs e) + { + next.OnFileChangedInProject (e); + } + + internal protected virtual void OnFilePropertyChangedInProject (ProjectFileEventArgs e) + { + next.OnFilePropertyChangedInProject (e); + } + + internal protected virtual void OnFileRenamedInProject (ProjectFileRenamedEventArgs e) + { + next.OnFileRenamedInProject (e); + } + + #endregion + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectFile.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectFile.cs index 77d9f63534..ad7d99b972 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectFile.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectFile.cs @@ -37,6 +37,7 @@ using MonoDevelop.Core; using MonoDevelop.Core.Serialization; using MonoDevelop.Projects; using MonoDevelop.Projects.Extensions; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { @@ -55,21 +56,98 @@ namespace MonoDevelop.Projects { } - public ProjectFile (string filename) + public ProjectFile (string filename): this (filename, MonoDevelop.Projects.BuildAction.Compile) { - this.filename = FileService.GetFullPath (filename); - subtype = Subtype.Code; - buildaction = MonoDevelop.Projects.BuildAction.Compile; } public ProjectFile (string filename, string buildAction) { this.filename = FileService.GetFullPath (filename); subtype = Subtype.Code; - buildaction = buildAction; + ItemName = buildaction = buildAction; + } + + public override string Include { + get { + if (project != null) { + string path = MSBuildProjectService.ToMSBuildPath (project.ItemDirectory, FilePath); + if (path.Length > 0) { + //directory paths must end with '/' + if ((Subtype == Subtype.Directory) && path [path.Length - 1] != '\\') + path = path + "\\"; + return path; + } + } + return base.Include; + } + protected set { + base.Include = value; + } + } + + internal protected override void Read (Project project, IMSBuildItemEvaluated buildItem) + { + base.Read (project, buildItem); + + if (buildItem.Name == "Folder") { + // Read folders + string path = MSBuildProjectService.FromMSBuildPath (project.ItemDirectory, buildItem.Include); + Name = Path.GetDirectoryName (path); + Subtype = Subtype.Directory; + return; + } + + Name = MSBuildProjectService.FromMSBuildPath (project.ItemDirectory, buildItem.Include); + BuildAction = buildItem.Name; + + DependsOn = buildItem.Metadata.GetPathValue ("DependentUpon", relativeToPath:FilePath.ParentDirectory); + + string copy = buildItem.Metadata.GetValue ("CopyToOutputDirectory"); + if (!string.IsNullOrEmpty (copy)) { + switch (copy) { + case "None": break; + case "Always": CopyToOutputDirectory = FileCopyMode.Always; break; + case "PreserveNewest": CopyToOutputDirectory = FileCopyMode.PreserveNewest; break; + default: + LoggingService.LogWarning ( + "Unrecognised value {0} for CopyToOutputDirectory MSBuild property", + copy); + break; + } + } + + Visible = buildItem.Metadata.GetValue ("Visible", true); + resourceId = buildItem.Metadata.GetValue ("LogicalName"); + contentType = buildItem.Metadata.GetValue ("SubType"); + generator = buildItem.Metadata.GetValue ("Generator"); + customToolNamespace = buildItem.Metadata.GetValue ("CustomToolNamespace"); + lastGenOutput = buildItem.Metadata.GetValue ("LastGenOutput"); + Link = buildItem.Metadata.GetPathValue ("Link", relativeToProject:false); } - [ItemProperty("subtype")] + internal protected override void Write (MSBuildFileFormat fmt, MSBuildItem buildItem) + { + base.Write (fmt, buildItem); + + buildItem.Metadata.SetValue ("DependentUpon", DependsOn, FilePath.Empty, relativeToPath:FilePath.ParentDirectory); + buildItem.Metadata.SetValue ("SubType", ContentType, ""); + buildItem.Metadata.SetValue ("Generator", Generator, ""); + buildItem.Metadata.SetValue ("CustomToolNamespace", CustomToolNamespace, ""); + buildItem.Metadata.SetValue ("LastGenOutput", LastGenOutput, ""); + buildItem.Metadata.SetValue ("Link", Link, FilePath.Empty, relativeToProject:false); + buildItem.Metadata.SetValue ("CopyToOutputDirectory", CopyToOutputDirectory.ToString (), "None"); + buildItem.Metadata.SetValue ("Visible", Visible, true); + + var resId = ResourceId; + + //For EmbeddedResource, emit LogicalName only when it does not match the default Id + if (BuildAction == MonoDevelop.Projects.BuildAction.EmbeddedResource && project.GetDefaultResourceId (this) == resId) + resId = ""; + + buildItem.Metadata.SetValue ("LogicalName", resId, ""); + } + + Subtype subtype; public Subtype Subtype { get { return subtype; } @@ -79,17 +157,6 @@ namespace MonoDevelop.Projects } } - [ItemProperty("data", DefaultValue = "")] - string data = ""; - public string Data { - get { return data; } - set { - data = value; - OnChanged ("Data"); - } - } - - public string Name { get { return filename; } @@ -117,8 +184,6 @@ namespace MonoDevelop.Projects } } - - [ItemProperty("buildaction")] string buildaction = MonoDevelop.Projects.BuildAction.None; public string BuildAction { get { return buildaction; } @@ -128,7 +193,6 @@ namespace MonoDevelop.Projects } } - [ItemProperty("resource_id", DefaultValue = "")] string resourceId = String.Empty; internal string GetResourceId (IResourceHandler resourceHandler) @@ -148,15 +212,6 @@ namespace MonoDevelop.Projects } /// <summary> - /// Set to true if this ProjectFile was created at load time by - /// a ProjectFile containing wildcards. If true, this instance - /// should not be saved to a csproj file. - /// </summary> - internal bool IsOriginatedFromWildcard { - get; set; - } - - /// <summary> /// The file should be treated as effectively having this relative path within the project. If the file is /// a link or outside the project root, this will not be the same as the physical file. /// </summary> @@ -179,17 +234,15 @@ namespace MonoDevelop.Projects get { return project; } } - [ItemProperty("SubType")] - string contentType = String.Empty; + string contentType; public string ContentType { - get { return contentType; } + get { return contentType ?? ""; } set { contentType = value; OnChanged ("ContentType"); } } - [ItemProperty("Visible", DefaultValue = true)] bool visible = true; /// <summary> @@ -205,14 +258,13 @@ namespace MonoDevelop.Projects } } - [ItemProperty("Generator", DefaultValue = "")] string generator; /// <summary> /// The ID of a custom code generator. /// </summary> public string Generator { - get { return generator; } + get { return generator ?? ""; } set { if (generator != value) { generator = value; @@ -221,14 +273,13 @@ namespace MonoDevelop.Projects } } - [ItemProperty("CustomToolNamespace", DefaultValue = "")] string customToolNamespace; /// <summary> /// Overrides the namespace in which the custom code generator should generate code. /// </summary> public string CustomToolNamespace { - get { return customToolNamespace; } + get { return customToolNamespace ?? ""; } set { if (customToolNamespace != value) { customToolNamespace = value; @@ -238,14 +289,13 @@ namespace MonoDevelop.Projects } - [ItemProperty("LastGenOutput", DefaultValue = "")] string lastGenOutput; /// <summary> /// The file most recently generated by the custom tool. Relative to this file's parent directory. /// </summary> public string LastGenOutput { - get { return lastGenOutput; } + get { return lastGenOutput ?? ""; } set { if (lastGenOutput != value) { lastGenOutput = value; @@ -254,8 +304,6 @@ namespace MonoDevelop.Projects } } - - [RelativeProjectPathItemProperty("Link", DefaultValue = "")] string link; /// <summary> @@ -263,7 +311,7 @@ namespace MonoDevelop.Projects /// within the project root. Use ProjectVirtualPath to read the effective virtual path for any file. /// </summary> public FilePath Link { - get { return link; } + get { return link ?? ""; } set { if (link != value) { if (value.IsAbsolute || value.ToString ().StartsWith ("..", StringComparison.Ordinal)) @@ -296,8 +344,7 @@ namespace MonoDevelop.Projects } } - [ItemProperty("copyToOutputDirectory", DefaultValue = FileCopyMode.None)] - FileCopyMode copyToOutputDirectory; + FileCopyMode copyToOutputDirectory = FileCopyMode.None; public FileCopyMode CopyToOutputDirectory { get { return copyToOutputDirectory; } set { @@ -311,7 +358,7 @@ namespace MonoDevelop.Projects #region File grouping string dependsOn; public string DependsOn { - get { return dependsOn; } + get { return dependsOn ?? ""; } set { if (dependsOn != value) { @@ -406,15 +453,18 @@ namespace MonoDevelop.Projects return resourceId; } set { - resourceId = value; - OnChanged ("ResourceId"); + if (resourceId != value) { + var oldVal = ResourceId; + resourceId = value; + if (ResourceId != oldVal) + OnChanged ("ResourceId"); + } } } internal void SetProject (Project project) { this.project = project; - if (project != null) OnVirtualPathChanged (FilePath.Null, ProjectVirtualPath); } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItem.cs index 8c5a7303fa..cb9934cd82 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItem.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItem.cs @@ -26,14 +26,16 @@ using System; using System.Collections; +using System.Collections.Generic; using MonoDevelop.Core.Serialization; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { public class ProjectItem: IExtendedDataItem { Hashtable extendedProperties; - + public IDictionary ExtendedProperties { get { if (extendedProperties == null) @@ -41,19 +43,42 @@ namespace MonoDevelop.Projects return extendedProperties; } } + + public void SetMetadata (string name, string value, bool isXml = false) + { + } + + public string GetMetadata (string name, string defaultValue = null) + { + return null; + } internal string Condition { get; set; } + public string ItemName { get; protected set; } + + public virtual string Include { get; protected set; } + + public string UnevaluatedInclude { get; protected set; } + public ProjectItemFlags Flags { get; set; } + + internal protected virtual void Read (Project project, IMSBuildItemEvaluated buildItem) + { + ItemName = buildItem.Name; + Include = buildItem.Include; + UnevaluatedInclude = buildItem.UnevaluatedInclude; + Condition = buildItem.Condition; + } + + internal protected virtual void Write (MSBuildFileFormat fmt, MSBuildItem buildItem) + { + buildItem.Condition = Condition; + } } public class UnknownProjectItem: ProjectItem { - public string ItemName { get; private set; } - - [ItemProperty ("Include")] - public string Include { get; private set; } - public UnknownProjectItem (string name, string include) { this.ItemName = name; diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemCollection.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemCollection.cs index cfdbd848dc..4a2badcff1 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemCollection.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemCollection.cs @@ -37,7 +37,7 @@ namespace MonoDevelop.Projects { } - internal ProjectItemCollection (SolutionEntityItem parent): base (parent) + internal ProjectItemCollection (SolutionItem parent): base (parent) { } } @@ -51,11 +51,11 @@ namespace MonoDevelop.Projects public class ProjectItemCollection<T>: ItemCollection<T>, IItemListHandler where T: ProjectItem { - SolutionEntityItem parent; + SolutionItem parent; IItemListHandler parentCollection; List<IItemListHandler> subCollections; - internal ProjectItemCollection (SolutionEntityItem parent) + internal ProjectItemCollection (SolutionItem parent) { this.parent = parent; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemEventArgs.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemEventArgs.cs index 50cbb2dd8e..806c633362 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemEventArgs.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectItemEventArgs.cs @@ -34,7 +34,7 @@ namespace MonoDevelop.Projects { } - public ProjectItemEventArgs (SolutionEntityItem solutionItem, ProjectItem item) + public ProjectItemEventArgs (SolutionItem solutionItem, ProjectItem item) { Add (new ProjectItemEventInfo (solutionItem, item)); } @@ -43,15 +43,15 @@ namespace MonoDevelop.Projects public class ProjectItemEventInfo { ProjectItem item; - SolutionEntityItem solutionItem; + SolutionItem solutionItem; - public ProjectItemEventInfo (SolutionEntityItem solutionItem, ProjectItem item) + public ProjectItemEventInfo (SolutionItem solutionItem, ProjectItem item) { this.item = item; this.solutionItem = solutionItem; } - public SolutionEntityItem SolutionItem { + public SolutionItem SolutionItem { get { return solutionItem; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectParameters.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectParameters.cs index 457111b18d..f78e021bc7 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectParameters.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectParameters.cs @@ -27,11 +27,12 @@ using System; using MonoDevelop.Core.Serialization; using MonoDevelop.Projects.Extensions; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { [DataItem (FallbackType=typeof(UnknownProjectParameters))] - public class ProjectParameters: ILoadController + public class ProjectParameters: ILoadController, IMSBuildDataObject { DotNetProject parentProject; @@ -69,5 +70,23 @@ namespace MonoDevelop.Projects protected virtual void OnEndLoad () { } + + void IMSBuildDataObject.Read (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + Read (pset, format); + } + + void IMSBuildDataObject.Write (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + Write (pset, format); + } + + protected virtual void Read (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + } + + protected virtual void Write (IMSBuildPropertySet pset, MSBuildFileFormat format) + { + } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectReference.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectReference.cs index 74e56794d8..a30115c441 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectReference.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectReference.cs @@ -37,6 +37,7 @@ using System.ComponentModel; using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; using MonoDevelop.Core.Assemblies; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { @@ -73,8 +74,11 @@ namespace MonoDevelop.Projects string package; SystemPackage cachedPackage; string customError; - string hintPath; - + FilePath hintPath; + + string originalMSBuildReferenceInclude; + string originalMSBuildReferenceHintPath; + public event EventHandler StatusChanged; [ItemProperty ("Package", DefaultValue="")] @@ -100,6 +104,19 @@ namespace MonoDevelop.Projects ownerProject = project; UpdatePackageReference (); } + + public sealed override string Include { + get { + if (referenceType == ReferenceType.Project && base.Include == null) { + Project refProj = OwnerProject != null && OwnerProject.ParentSolution != null ? OwnerProject.ParentSolution.FindProjectByName (Reference) : null; + if (refProj != null) + base.Include = MSBuildProjectService.ToMSBuildPath (OwnerProject.ItemDirectory, refProj.FileName); + else + base.Include = Reference; + } + return base.Include; + } + } public ProjectReference (ReferenceType referenceType, string reference): this (referenceType, reference, null) { @@ -107,20 +124,66 @@ namespace MonoDevelop.Projects public ProjectReference (ReferenceType referenceType, string reference, string hintPath) { + Init (referenceType, reference, hintPath); + } + + void Init (ReferenceType referenceType, string reference, string hintPath) + { if (referenceType == ReferenceType.Assembly) { specificVersion = false; if (hintPath == null) { hintPath = reference; reference = Path.GetFileNameWithoutExtension (reference); } + + if (Include == null) { + if (File.Exists (HintPath)) { + try { + var aname = System.Reflection.AssemblyName.GetAssemblyName (HintPath); + if (SpecificVersion) { + Include = aname.FullName; + } else { + Include = aname.Name; + } + } catch (Exception ex) { + string msg = string.Format ("Could not get full name for assembly '{0}'.", Reference); + LoggingService.LogError (msg, ex); + } + } + if (Include == null) + Include = Path.GetFileNameWithoutExtension (hintPath); + } + } + + switch (referenceType) { + case ReferenceType.Package: + case ReferenceType.Assembly: + ItemName = "Reference"; + break; + case ReferenceType.Project: + ItemName = "ProjectReference"; + break; } this.referenceType = referenceType; this.reference = reference; this.hintPath = hintPath; UpdatePackageReference (); + + if (referenceType == ReferenceType.Package && Include == null) { + Include = StoredReference; + SystemPackage pkg = Package; + if (pkg != null && pkg.IsFrameworkPackage) { + int i = Include.IndexOf (','); + if (i != -1) + Include = Include.Substring (0, i).Trim (); + } + } + + if (Include == null) + Include = reference; } - + public ProjectReference (Project referencedProject) { referenceType = ReferenceType.Project; @@ -138,7 +201,120 @@ namespace MonoDevelop.Projects package = asm.Package.Name; UpdatePackageReference (); } - + + internal protected override void Read (Project project, IMSBuildItemEvaluated buildItem) + { + base.Read (project, buildItem); + + if (buildItem.Name == "Reference") + ReadReference (project, buildItem); + else if (buildItem.Name == "ProjectReference") + ReadProjectReference (project, buildItem); + + LocalCopy = buildItem.Metadata.GetValue ("Private", DefaultLocalCopy); + } + + void ReadReference (Project project, IMSBuildItemEvaluated buildItem) + { + if (buildItem.Metadata.HasProperty ("HintPath")) { + FilePath path; + var p = buildItem.Metadata.GetProperty ("HintPath"); + if (p != null) + originalMSBuildReferenceHintPath = p.UnevaluatedValue; + if (!buildItem.Metadata.TryGetPathValue ("HintPath", out path)) { + var hp = buildItem.Metadata.GetValue ("HintPath"); + Init (ReferenceType.Assembly, hp, null); + SetInvalid (GettextCatalog.GetString ("Invalid file path")); + originalMSBuildReferenceInclude = buildItem.Include; + } else { + var type = File.Exists (path) ? ReferenceType.Assembly : ReferenceType.Package; + Init (type, buildItem.Include, path); + } + } else { + string asm = buildItem.Include; + // This is a workaround for a VS bug. Looks like it is writing this assembly incorrectly + if (asm == "System.configuration") + asm = "System.Configuration"; + else if (asm == "System.XML") + asm = "System.Xml"; + else if (asm == "system") + asm = "System"; + Init (ReferenceType.Package, asm, null); + } + + string specificVersion = buildItem.Metadata.GetValue ("SpecificVersion"); + if (string.IsNullOrWhiteSpace (specificVersion)) { + // If the SpecificVersion element isn't present, check if the Assembly Reference specifies a Version + SpecificVersion = ReferenceStringHasVersion (buildItem.Include); + } + else { + bool value; + // if we can't parse the value, default to false which is more permissive + SpecificVersion = bool.TryParse (specificVersion, out value) && value; + } + } + + void ReadProjectReference (Project project, IMSBuildItemEvaluated buildItem) + { + // Get the project name from the path, since the Name attribute may other stuff other than the name + string path = MSBuildProjectService.FromMSBuildPath (project.ItemDirectory, buildItem.Include); + string name = Path.GetFileNameWithoutExtension (path); + Init (ReferenceType.Project, name, null); + } + + internal protected override void Write (MSBuildFileFormat fmt, MSBuildItem buildItem) + { + // If the project is not supported, don't try to update any metadata of the property, + // just leave what was read + if (OwnerProject.IsUnsupportedProject) + return; + + base.Write (fmt, buildItem); + + if (ReferenceType == ReferenceType.Assembly) { + if (originalMSBuildReferenceHintPath != null) + buildItem.Metadata.SetValue ("HintPath", originalMSBuildReferenceHintPath, ""); + else + buildItem.Metadata.SetValue ("HintPath", HintPath); + + buildItem.Metadata.SetValue ("SpecificVersion", SpecificVersion || !ReferenceStringHasVersion (Include), true); + } + else if (ReferenceType == ReferenceType.Package) { + buildItem.Metadata.SetValue ("SpecificVersion", SpecificVersion || !ReferenceStringHasVersion (Include), true); + + //RequiredTargetFramework is undocumented, maybe only a hint for VS. Only seems to be used for .NETFramework + var dnp = OwnerProject as DotNetProject; + IList supportedFrameworks = fmt.SupportedFrameworks; + if (supportedFrameworks != null && dnp != null && Package != null + && dnp.TargetFramework.Id.Identifier == TargetFrameworkMoniker.ID_NET_FRAMEWORK + && Package.IsFrameworkPackage && supportedFrameworks.Contains (Package.TargetFramework) + && Package.TargetFramework.Version != "2.0" && supportedFrameworks.Count > 1) + { + TargetFramework fx = Runtime.SystemAssemblyService.GetTargetFramework (Package.TargetFramework); + buildItem.Metadata.SetValue ("RequiredTargetFramework", fx.Id.Version); + } else { + buildItem.Metadata.RemoveProperty ("RequiredTargetFramework"); + } + + buildItem.Metadata.SetValue ("HintPath", originalMSBuildReferenceHintPath, ""); + } + else if (ReferenceType == ReferenceType.Project) { + Project refProj = OwnerProject.ParentSolution.FindProjectByName (Reference); + if (refProj != null) { + buildItem.Metadata.SetValue ("Project", refProj.ItemId); + buildItem.Metadata.SetValue ("Name", refProj.Name); + } + } + + buildItem.Metadata.SetValue ("Private", LocalCopy, DefaultLocalCopy); + } + + bool ReferenceStringHasVersion (string asmName) + { + int commaPos = asmName.IndexOf (','); + return commaPos >= 0 && asmName.IndexOf ("Version", commaPos) >= 0; + } + protected void InitCustomReference (string reference) { Reference = reference; @@ -256,8 +432,7 @@ namespace MonoDevelop.Projects if (notFound) { if (ownerProject != null) { bool isDefaultRuntime = Runtime.SystemAssemblyService.DefaultRuntime == TargetRuntime; - var hintPath = ExtendedProperties ["_OriginalMSBuildReferenceHintPath"] as string; - bool probablyFrameworkAssembly = string.IsNullOrEmpty (hintPath); + bool probablyFrameworkAssembly = string.IsNullOrEmpty (originalMSBuildReferenceHintPath); if (TargetRuntime.IsInstalled (TargetFramework) || !probablyFrameworkAssembly) { if (isDefaultRuntime) @@ -307,7 +482,7 @@ namespace MonoDevelop.Projects } } - public string HintPath { + public FilePath HintPath { get { return hintPath; } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectService.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectService.cs index 64d8bc6e76..fa493fb8f7 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectService.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectService.cs @@ -26,28 +26,22 @@ using System; using System.Collections; -using System.Collections.Specialized; using System.Collections.Generic; -using System.Diagnostics; using System.IO; using System.Xml; -using System.CodeDom.Compiler; -using System.Threading; using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; using MonoDevelop.Core; using Mono.Addins; -using MonoDevelop.Core.ProgressMonitoring; -using MonoDevelop.Core.Execution; using MonoDevelop.Core.Assemblies; using MonoDevelop.Core.Instrumentation; using MonoDevelop.Projects.Extensions; using Mono.Unix; -using MonoDevelop.Core.StringParsing; using System.Linq; using MonoDevelop.Projects.Formats.MSBuild; +using System.Threading.Tasks; namespace MonoDevelop.Projects { @@ -63,7 +57,7 @@ namespace MonoDevelop.Projects TargetFramework defaultTargetFramework; string defaultPlatformTarget = "x86"; - static readonly TargetFrameworkMoniker DefaultTargetFrameworkId = TargetFrameworkMoniker.NET_4_0; + static readonly TargetFrameworkMoniker DefaultTargetFrameworkId = TargetFrameworkMoniker.NET_4_5; public const string BuildTarget = "Build"; public const string CleanTarget = "Clean"; @@ -72,7 +66,9 @@ namespace MonoDevelop.Projects const string SerializableClassesExtensionPath = "/MonoDevelop/ProjectModel/SerializableClasses"; const string ExtendedPropertiesExtensionPath = "/MonoDevelop/ProjectModel/ExtendedProperties"; const string ProjectBindingsExtensionPath = "/MonoDevelop/ProjectModel/ProjectBindings"; - + + internal const string ProjectModelExtensionsPath = "/MonoDevelop/ProjectModel/ProjectModelExtensions"; + internal event EventHandler DataContextChanged; class ExtensionChainInfo @@ -101,7 +97,7 @@ namespace MonoDevelop.Projects get { return formatManager; } } - internal ProjectServiceExtension GetExtensionChain (IBuildTarget target) + internal ProjectServiceExtension GetExtensionChain (WorkspaceObject target) { ProjectServiceExtension chain; if (target != null) { @@ -147,18 +143,14 @@ namespace MonoDevelop.Projects ProjectServiceExtension CreateExtensionChain (ProjectServiceExtension[] extensions) { - var first = new CustomCommandExtension (); - - for (int n=0; n<extensions.Length - 1; n++) - extensions [n].Next = extensions [n + 1]; - if (extensions.Length > 0) { + for (int n=0; n<extensions.Length - 1; n++) + extensions [n].Next = extensions [n + 1]; extensions [extensions.Length - 1].Next = extensionChainTerminator; - first.Next = extensions [0]; + return extensions [0]; } else { - first.Next = extensionChainTerminator; + return extensionChainTerminator; } - return first; } public string DefaultPlatformTarget { @@ -191,16 +183,16 @@ namespace MonoDevelop.Projects return formats [0]; } - public SolutionEntityItem ReadSolutionItem (IProgressMonitor monitor, string file) + public async Task<SolutionItem> ReadSolutionItem (ProgressMonitor monitor, string file) { file = Path.GetFullPath (file); using (Counters.ReadSolutionItem.BeginTiming ("Read project " + file)) { file = GetTargetFile (file); - SolutionEntityItem loadedItem = GetExtensionChain (null).LoadSolutionItem (monitor, file, delegate { - FileFormat format; - SolutionEntityItem item = ReadFile (monitor, file, typeof(SolutionEntityItem), out format) as SolutionEntityItem; + SolutionItem loadedItem = await GetExtensionChain (null).LoadSolutionItem (monitor, file, async delegate { + var res = await ReadFile (monitor, file, typeof(SolutionItem)); + SolutionItem item = res.Item1 as SolutionItem; if (item != null) - item.FileFormat = format; + item.FileFormat = res.Item2; else throw new InvalidOperationException ("Invalid file format: " + file); return item; @@ -210,23 +202,23 @@ namespace MonoDevelop.Projects } } - public SolutionItem ReadSolutionItem (IProgressMonitor monitor, SolutionItemReference reference, params WorkspaceItem[] workspaces) + public async Task<SolutionFolderItem> ReadSolutionItem (ProgressMonitor monitor, SolutionItemReference reference, params WorkspaceItem[] workspaces) { if (reference.Id == null) { FilePath file = reference.Path.FullPath; foreach (WorkspaceItem workspace in workspaces) { - foreach (SolutionEntityItem eitem in workspace.GetAllSolutionItems<SolutionEntityItem> ()) + foreach (SolutionItem eitem in workspace.GetAllItems<Solution>().SelectMany (s => s.GetAllSolutionItems ())) if (file == eitem.FileName) return eitem; } - return ReadSolutionItem (monitor, reference.Path); + return await ReadSolutionItem (monitor, reference.Path); } else { Solution sol = null; if (workspaces.Length > 0) { FilePath file = reference.Path.FullPath; foreach (WorkspaceItem workspace in workspaces) { - foreach (Solution item in workspace.GetAllSolutions ()) { + foreach (Solution item in workspace.GetAllItems<Solution>()) { if (item.FileName.FullPath == file) { sol = item; break; @@ -237,7 +229,7 @@ namespace MonoDevelop.Projects } } if (sol == null) - sol = ReadWorkspaceItem (monitor, reference.Path) as Solution; + sol = await ReadWorkspaceItem (monitor, reference.Path) as Solution; if (reference.Id == ":root:") return sol.RootFolder; @@ -246,12 +238,12 @@ namespace MonoDevelop.Projects } } - public WorkspaceItem ReadWorkspaceItem (IProgressMonitor monitor, string file) + public async Task<WorkspaceItem> ReadWorkspaceItem (ProgressMonitor monitor, string file) { file = Path.GetFullPath (file); using (Counters.ReadWorkspaceItem.BeginTiming ("Read solution " + file)) { file = GetTargetFile (file); - WorkspaceItem item = GetExtensionChain (null).LoadWorkspaceItem (monitor, file) as WorkspaceItem; + WorkspaceItem item = await GetExtensionChain (null).LoadWorkspaceItem (monitor, file) as WorkspaceItem; if (item != null) item.NeedsReload = false; else @@ -260,54 +252,45 @@ namespace MonoDevelop.Projects } } - internal void InternalWriteSolutionItem (IProgressMonitor monitor, FilePath file, SolutionEntityItem item) - { - var newFile = WriteFile (monitor, file, item, null); - if (newFile != null) - item.FileName = newFile; - else - throw new InvalidOperationException ("FileFormat not provided for solution item '" + item.Name + "'"); - } - - internal WorkspaceItem InternalReadWorkspaceItem (string file, IProgressMonitor monitor) + internal async Task<WorkspaceItem> InternalReadWorkspaceItem (string file, ProgressMonitor monitor) { - FileFormat format; - WorkspaceItem item = ReadFile (monitor, file, typeof(WorkspaceItem), out format) as WorkspaceItem; + var res = await ReadFile (monitor, file, typeof(WorkspaceItem)); + WorkspaceItem item = res.Item1 as WorkspaceItem; if (item == null) throw new InvalidOperationException ("Invalid file format: " + file); if (!item.FormatSet) - item.ConvertToFormat (format, false); + await item.ConvertToFormat (res.Item2, false); return item; } - internal void InternalWriteWorkspaceItem (IProgressMonitor monitor, FilePath file, WorkspaceItem item) + internal async Task InternalWriteWorkspaceItem (ProgressMonitor monitor, FilePath file, WorkspaceItem item) { - var newFile = WriteFile (monitor, file, item, item.FileFormat); + var newFile = await WriteFile (monitor, file, item, item.FileFormat); if (newFile != null) item.FileName = newFile; else throw new InvalidOperationException ("FileFormat not provided for workspace item '" + item.Name + "'"); } - object ReadFile (IProgressMonitor monitor, string file, Type expectedType, out FileFormat format) + async Task<Tuple<object,FileFormat>> ReadFile (ProgressMonitor monitor, string file, Type expectedType) { FileFormat[] formats = formatManager.GetFileFormats (file, expectedType); if (formats.Length == 0) throw new InvalidOperationException ("Unknown file format: " + file); - format = formats [0]; - object obj = format.Format.ReadFile (file, expectedType, monitor); + var format = formats [0]; + object obj = await format.Format.ReadFile (file, expectedType, monitor); if (obj == null) throw new InvalidOperationException ("Invalid file format: " + file); - return obj; + return new Tuple<object,FileFormat> (obj, format); } - FilePath WriteFile (IProgressMonitor monitor, FilePath file, object item, FileFormat format) + async Task<FilePath> WriteFile (ProgressMonitor monitor, FilePath file, object item, FileFormat format) { if (format == null) { if (defaultFormat.CanWrite (item)) @@ -325,33 +308,33 @@ namespace MonoDevelop.Projects FileService.RequestFileEdit (file); - format.Format.WriteFile (file, item, monitor); + await format.Format.WriteFile (file, item, monitor); return file; } - public string Export (IProgressMonitor monitor, string rootSourceFile, string targetPath, FileFormat format) + public Task<string> Export (ProgressMonitor monitor, string rootSourceFile, string targetPath, FileFormat format) { rootSourceFile = GetTargetFile (rootSourceFile); return Export (monitor, rootSourceFile, null, targetPath, format); } - public string Export (IProgressMonitor monitor, string rootSourceFile, string[] includedChildIds, string targetPath, FileFormat format) + public async Task<string> Export (ProgressMonitor monitor, string rootSourceFile, string[] includedChildIds, string targetPath, FileFormat format) { IWorkspaceFileObject obj; if (IsWorkspaceItemFile (rootSourceFile)) { - obj = ReadWorkspaceItem (monitor, rootSourceFile) as Solution; + obj = await ReadWorkspaceItem (monitor, rootSourceFile) as Solution; } else { - obj = ReadSolutionItem (monitor, rootSourceFile); + obj = await ReadSolutionItem (monitor, rootSourceFile); if (obj == null) throw new InvalidOperationException ("File is not a solution or project."); } using (obj) { - return Export (monitor, obj, includedChildIds, targetPath, format); + return await Export (monitor, obj, includedChildIds, targetPath, format); } } - string Export (IProgressMonitor monitor, IWorkspaceFileObject obj, string[] includedChildIds, string targetPath, FileFormat format) + async Task<string> Export (ProgressMonitor monitor, IWorkspaceFileObject obj, string[] includedChildIds, string targetPath, FileFormat format) { string rootSourceFile = obj.FileName; string sourcePath = Path.GetFullPath (Path.GetDirectoryName (rootSourceFile)); @@ -363,17 +346,17 @@ namespace MonoDevelop.Projects string newFile = Path.Combine (targetPath, Path.GetFileName (rootSourceFile)); if (IsWorkspaceItemFile (rootSourceFile)) - obj = ReadWorkspaceItem (monitor, newFile); + obj = await ReadWorkspaceItem (monitor, newFile); else - obj = (SolutionEntityItem) ReadSolutionItem (monitor, newFile); + obj = (SolutionItem) await ReadSolutionItem (monitor, newFile); using (obj) { - List<FilePath> oldFiles = obj.GetItemFiles (true); + var oldFiles = obj.GetItemFiles (true).ToList (); ExcludeEntries (obj, includedChildIds); if (format != null) - obj.ConvertToFormat (format, true); - obj.Save (monitor);
- List<FilePath> newFiles = obj.GetItemFiles (true); + await obj.ConvertToFormat (format, true); + await obj.SaveAsync (monitor);
+ var newFiles = obj.GetItemFiles (true); foreach (FilePath f in newFiles) { if (!f.IsChildPathOf (targetPath)) { @@ -408,8 +391,8 @@ namespace MonoDevelop.Projects using (obj) { ExcludeEntries (obj, includedChildIds); if (format != null) - obj.ConvertToFormat (format, true); - obj.Save (monitor); + await obj.ConvertToFormat (format, true); + await obj.SaveAsync (monitor); return obj.FileName; } } @@ -425,14 +408,14 @@ namespace MonoDevelop.Projects foreach (string it in includedChildIds) childIds [it] = it; - foreach (SolutionItem item in sol.GetAllSolutionItems<SolutionItem> ()) { + foreach (SolutionFolderItem item in sol.GetAllItems<SolutionFolderItem> ()) { if (!childIds.ContainsKey (item.ItemId) && item.ParentFolder != null) item.ParentFolder.Items.Remove (item); } } }
- bool CopyFiles (IProgressMonitor monitor, IWorkspaceFileObject obj, IEnumerable<FilePath> files, FilePath targetBasePath, bool ignoreExternalFiles) + bool CopyFiles (ProgressMonitor monitor, IWorkspaceFileObject obj, IEnumerable<FilePath> files, FilePath targetBasePath, bool ignoreExternalFiles) {
FilePath baseDir = obj.BaseDirectory.FullPath;
foreach (FilePath file in files) { @@ -465,51 +448,28 @@ namespace MonoDevelop.Projects return true; } - public bool CanCreateSingleFileProject (string file) + public DotNetProject CreateDotNetProject (string language) { - foreach (ProjectBindingCodon projectBinding in projectBindings) { - if (projectBinding.ProjectBinding.CanCreateSingleFileProject (file)) - return true; - } - return false; + string typeGuid = MSBuildProjectService.GetLanguageGuid (language); + return (DotNetProject) MSBuildProjectService.CreateSolutionItem (typeGuid); } - - public Project CreateSingleFileProject (string file) - { - foreach (ProjectBindingCodon projectBinding in projectBindings) { - if (projectBinding.ProjectBinding.CanCreateSingleFileProject (file)) { - return projectBinding.ProjectBinding.CreateSingleFileProject (file); - } - } - return null; - } - - public Project CreateProject (string type, ProjectCreateInformation info, XmlElement projectOptions) + + public Project CreateProject (string typeAlias, ProjectCreateInformation info, XmlElement projectOptions) { - foreach (ProjectBindingCodon projectBinding in projectBindings) { - if (projectBinding.ProjectBinding.Name == type) { - Project project = projectBinding.ProjectBinding.CreateProject (info, projectOptions); - return project; - } - } - throw new InvalidOperationException ("Project type '" + type + "' not found"); + return MSBuildProjectService.CreateSolutionItem (typeAlias, info, projectOptions) as Project; } - public bool CanCreateProject (string type) + public bool CanCreateProject (string typeAlias, ProjectCreateInformation info, XmlElement projectOptions) { - foreach (ProjectBindingCodon projectBinding in projectBindings) { - if (projectBinding.ProjectBinding.Name == type) - return true; - } - return false; + return MSBuildProjectService.CanCreateSolutionItem (typeAlias, info, projectOptions); } //TODO: find solution that contains the project if possible - public Solution GetWrapperSolution (IProgressMonitor monitor, string filename) + public async Task<Solution> GetWrapperSolution (ProgressMonitor monitor, string filename) { // First of all, check if a solution with the same name already exists - FileFormat[] formats = Services.ProjectService.FileFormats.GetFileFormats (filename, typeof(SolutionEntityItem)); + FileFormat[] formats = Services.ProjectService.FileFormats.GetFileFormats (filename, typeof(SolutionItem)); if (formats.Length == 0) formats = new [] { DefaultFileFormat }; @@ -520,16 +480,16 @@ namespace MonoDevelop.Projects string solFileName = solutionFileFormat.GetValidFileName (tempSolution, filename); if (File.Exists (solFileName)) { - return (Solution) Services.ProjectService.ReadWorkspaceItem (monitor, solFileName); + return (Solution) await Services.ProjectService.ReadWorkspaceItem (monitor, solFileName); } else { // Create a temporary solution and add the project to the solution tempSolution.SetLocation (Path.GetDirectoryName (filename), Path.GetFileNameWithoutExtension (filename)); - SolutionEntityItem sitem = Services.ProjectService.ReadSolutionItem (monitor, filename); - tempSolution.ConvertToFormat (solutionFileFormat, false); + SolutionItem sitem = await Services.ProjectService.ReadSolutionItem (monitor, filename); + await tempSolution.ConvertToFormat (solutionFileFormat, false); tempSolution.RootFolder.Items.Add (sitem); tempSolution.CreateDefaultConfigurations (); - tempSolution.Save (monitor); + await tempSolution.SaveAsync (monitor); return tempSolution; } } @@ -552,7 +512,7 @@ namespace MonoDevelop.Projects internal bool IsSolutionItemFileInternal (string filename) { - return formatManager.GetFileFormats (filename, typeof(SolutionItem)).Length > 0; + return formatManager.GetFileFormats (filename, typeof(SolutionFolderItem)).Length > 0; } internal bool IsWorkspaceItemFileInternal (string filename) @@ -634,34 +594,6 @@ namespace MonoDevelop.Projects internal class DefaultProjectServiceExtension: ProjectServiceExtension { - Dictionary <SolutionItem,bool> needsBuildingCache; - - public override object GetService (SolutionItem item, Type type) - { - return item.OnGetService (type); - } - - public override object GetService (WorkspaceItem item, Type type) - { - return item.OnGetService (type); - } - - public override void Save (IProgressMonitor monitor, SolutionEntityItem entry) - { - FileService.RequestFileEdit (entry.GetItemFiles (false)); - entry.OnSave (monitor); - } - - public override void Save (IProgressMonitor monitor, WorkspaceItem entry) - { - entry.OnSave (monitor); - }
-
- public override List<FilePath> GetItemFiles (SolutionEntityItem entry, bool includeReferencedFiles) - { - return entry.OnGetItemFiles (includeReferencedFiles); - } - public override bool IsSolutionItemFile (string filename) { return Services.ProjectService.IsSolutionItemFileInternal (filename); @@ -672,152 +604,15 @@ namespace MonoDevelop.Projects return Services.ProjectService.IsWorkspaceItemFileInternal (filename); } - internal override SolutionEntityItem LoadSolutionItem (IProgressMonitor monitor, string fileName, ItemLoadCallback callback) + internal override Task<SolutionItem> LoadSolutionItem (ProgressMonitor monitor, string fileName, ItemLoadCallback callback) { return callback (monitor, fileName); } - public override WorkspaceItem LoadWorkspaceItem (IProgressMonitor monitor, string fileName) + public override Task<WorkspaceItem> LoadWorkspaceItem (ProgressMonitor monitor, string fileName) { return Services.ProjectService.InternalReadWorkspaceItem (fileName, monitor); } - - public override BuildResult RunTarget (IProgressMonitor monitor, IBuildTarget item, string target, ConfigurationSelector configuration) - { - BuildResult res; - if (item is WorkspaceItem) { - res = ((WorkspaceItem)item).OnRunTarget (monitor, target, configuration); - } - else if (item is SolutionItem) - res = ((SolutionItem)item).OnRunTarget (monitor, target, configuration); - else - throw new InvalidOperationException ("Unknown item type: " + item); - - if (res != null) - res.SourceTarget = item; - return res; - } - - public override bool SupportsTarget (IBuildTarget item, string target) - { - if (item is WorkspaceItem) - return ((WorkspaceItem)item).OnGetSupportsTarget (target); - else if (item is SolutionItem) - return ((SolutionItem)item).OnGetSupportsTarget (target); - else - throw new InvalidOperationException ("Unknown item type: " + item); - } - - public override bool SupportsExecute (IBuildTarget item) - { - if (item is WorkspaceItem) - return ((WorkspaceItem)item).OnGetSupportsExecute (); - else if (item is SolutionItem) - return ((SolutionItem)item).OnGetSupportsExecute (); - else - throw new InvalidOperationException ("Unknown item type: " + item); - } - - public override void Execute (IProgressMonitor monitor, IBuildTarget item, ExecutionContext context, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) { - SolutionEntityItem entry = (SolutionEntityItem) item; - SolutionItemConfiguration conf = entry.GetConfiguration (configuration) as SolutionItemConfiguration; - if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Execute)) { - conf.CustomCommands.ExecuteCommand (monitor, entry, CustomCommandType.Execute, context, configuration); - return; - } - entry.OnExecute (monitor, context, configuration); - } - else if (item is WorkspaceItem) { - ((WorkspaceItem)item).OnExecute (monitor, context, configuration); - } - else if (item is SolutionItem) - ((SolutionItem)item).OnExecute (monitor, context, configuration); - else - throw new InvalidOperationException ("Unknown item type: " + item); - } - - public override bool CanExecute (IBuildTarget item, ExecutionContext context, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) { - SolutionEntityItem entry = (SolutionEntityItem) item; - SolutionItemConfiguration conf = entry.GetConfiguration (configuration) as SolutionItemConfiguration; - if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Execute)) - return conf.CustomCommands.CanExecute (entry, CustomCommandType.Execute, context, configuration); - return entry.OnGetCanExecute (context, configuration); - } - else if (item is WorkspaceItem) { - return ((WorkspaceItem)item).OnGetCanExecute (context, configuration); - } - else if (item is SolutionItem) - return ((SolutionItem)item).OnGetCanExecute (context, configuration); - else - throw new InvalidOperationException ("Unknown item type: " + item); - } - - public override IEnumerable<ExecutionTarget> GetExecutionTargets (IBuildTarget item, ConfigurationSelector configuration) - { - if (item is WorkspaceItem) { - return ((WorkspaceItem)item).OnGetExecutionTargets (configuration); - } - else if (item is SolutionItem) - return ((SolutionItem)item).OnGetExecutionTargets (configuration); - else - throw new InvalidOperationException ("Unknown item type: " + item); - } - - public override bool GetNeedsBuilding (IBuildTarget item, ConfigurationSelector configuration) - { - if (item is SolutionItem) { - SolutionItem entry = (SolutionItem) item; - // This is a cache to avoid unneeded recursive calls to GetNeedsBuilding. - bool cleanCache = false; - if (needsBuildingCache == null) { - needsBuildingCache = new Dictionary <SolutionItem,bool> (); - cleanCache = true; - } else { - bool res; - if (needsBuildingCache.TryGetValue (entry, out res)) - return res; - } - - bool nb = entry.OnGetNeedsBuilding (configuration); - - needsBuildingCache [entry] = nb; - if (cleanCache) - needsBuildingCache = null; - return nb; - } - else if (item is WorkspaceItem) { - return ((WorkspaceItem)item).OnGetNeedsBuilding (configuration); - } - else - throw new InvalidOperationException ("Unknown item type: " + item); - } - - public override void SetNeedsBuilding (IBuildTarget item, bool val, ConfigurationSelector configuration) - { - if (item is SolutionItem) { - SolutionItem entry = (SolutionItem) item; - entry.OnSetNeedsBuilding (val, configuration); - } - else if (item is WorkspaceItem) { - ((WorkspaceItem)item).OnSetNeedsBuilding (val, configuration); - } - else - throw new InvalidOperationException ("Unknown item type: " + item); - } - - internal override BuildResult Compile(IProgressMonitor monitor, SolutionEntityItem item, BuildData buildData, ItemCompileCallback callback) - { - return callback (monitor, item, buildData); - } - - public override IEnumerable<string> GetReferencedAssemblies (DotNetProject project, ConfigurationSelector configuration, bool includeProjectReferences) - { - return project.OnGetReferencedAssemblies (configuration, includeProjectReferences); - } } internal static class Counters @@ -826,7 +621,7 @@ namespace MonoDevelop.Projects public static Counter ItemsLoaded = InstrumentationService.CreateCounter ("Projects loaded", "Project Model"); public static Counter SolutionsInMemory = InstrumentationService.CreateCounter ("Solutions in memory", "Project Model"); public static Counter SolutionsLoaded = InstrumentationService.CreateCounter ("Solutions loaded", "Project Model"); - public static TimerCounter ReadWorkspaceItem = InstrumentationService.CreateTimerCounter ("Workspace item read", "Project Model"); + public static TimerCounter ReadWorkspaceItem = InstrumentationService.CreateTimerCounter ("Workspace item read", "Project Model", id:"Core.ReadWorkspaceItem"); public static TimerCounter ReadSolutionItem = InstrumentationService.CreateTimerCounter ("Solution item read", "Project Model"); public static TimerCounter ReadMSBuildProject = InstrumentationService.CreateTimerCounter ("MSBuild project read", "Project Model"); public static TimerCounter WriteMSBuildProject = InstrumentationService.CreateTimerCounter ("MSBuild project written", "Project Model"); diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectServiceExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectServiceExtension.cs index 476081baf6..08d368c82e 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectServiceExtension.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/ProjectServiceExtension.cs @@ -31,6 +31,7 @@ using System.Collections.Generic; using MonoDevelop.Core; using MonoDevelop.Projects.Extensions; using MonoDevelop.Core.Execution; +using System.Threading.Tasks; namespace MonoDevelop.Projects { @@ -39,9 +40,8 @@ namespace MonoDevelop.Projects internal ProjectServiceExtension Next; Stack<ItemLoadCallback> loadCallbackStack = new Stack<ItemLoadCallback> (); - Stack<ItemCompileCallback> compileCallbackStack = new Stack<ItemCompileCallback> (); - - internal ProjectServiceExtension GetNext (IBuildTarget item) + + internal ProjectServiceExtension GetNext (WorkspaceObject item) { if (Next.SupportsItem (item)) return Next; @@ -49,42 +49,11 @@ namespace MonoDevelop.Projects return Next.GetNext (item); } - public virtual bool SupportsItem (IBuildTarget item) + public virtual bool SupportsItem (WorkspaceObject item) { return true; } - public virtual object GetService (SolutionItem item, Type type) - { - if (type.IsInstanceOfType (this)) - return this; - else - return GetNext (item).GetService (item, type); - } - - public virtual object GetService (WorkspaceItem item, Type type) - { - if (type.IsInstanceOfType (this)) - return this; - else - return GetNext (item).GetService (item, type); - } - - public virtual void Save (IProgressMonitor monitor, SolutionEntityItem item) - { - GetNext (item).Save (monitor, item); - } - - public virtual void Save (IProgressMonitor monitor, WorkspaceItem item) - { - GetNext (item).Save (monitor, item); - }
-
- public virtual List<FilePath> GetItemFiles (SolutionEntityItem item, bool includeReferencedFiles) - { - return GetNext (item).GetItemFiles (item, includeReferencedFiles); - } - public virtual bool IsSolutionItemFile (string fileName) { return GetNext (UnknownItem.Instance).IsSolutionItemFile (fileName); @@ -95,307 +64,25 @@ namespace MonoDevelop.Projects return GetNext (UnknownItem.Instance).IsWorkspaceItemFile (fileName); } - internal virtual SolutionEntityItem LoadSolutionItem (IProgressMonitor monitor, string fileName, ItemLoadCallback callback) + internal async virtual Task<SolutionItem> LoadSolutionItem (ProgressMonitor monitor, string fileName, ItemLoadCallback callback) { loadCallbackStack.Push (callback); try { - SolutionEntityItem res = LoadSolutionItem (monitor, fileName); - return res; + return await LoadSolutionItem (monitor, fileName); } finally { loadCallbackStack.Pop (); } } - protected virtual SolutionEntityItem LoadSolutionItem (IProgressMonitor monitor, string fileName) + protected virtual Task<SolutionItem> LoadSolutionItem (ProgressMonitor monitor, string fileName) { return GetNext (UnknownItem.Instance).LoadSolutionItem (monitor, fileName, loadCallbackStack.Peek ()); } - public virtual WorkspaceItem LoadWorkspaceItem (IProgressMonitor monitor, string fileName) + public virtual Task<WorkspaceItem> LoadWorkspaceItem (ProgressMonitor monitor, string fileName) { return GetNext (UnknownItem.Instance).LoadWorkspaceItem (monitor, fileName); } - - public virtual BuildResult RunTarget (IProgressMonitor monitor, IBuildTarget item, string target, ConfigurationSelector configuration) - { - if (target == ProjectService.BuildTarget) - return Build (monitor, item, configuration); - else if (target == ProjectService.CleanTarget) { - Clean (monitor, item, configuration); - return null; - } - else - return GetNext (item).RunTarget (monitor, item, target, configuration); - } - - public virtual bool SupportsTarget (IBuildTarget item, string target) - { - if (item is SolutionEntityItem) - return SupportsTarget ((SolutionEntityItem)item, target); - else if (item is WorkspaceItem) - return SupportsTarget ((WorkspaceItem) item, target); - else - return GetNext (item).SupportsTarget (item, target); - } - - protected virtual bool SupportsTarget (SolutionEntityItem item, string target) - { - return GetNext (item).SupportsTarget ((IBuildTarget) item, target); - } - - protected virtual bool SupportsTarget (Solution solution, string target) - { - return GetNext (solution).SupportsTarget ((IBuildTarget) solution, target); - } - - protected virtual bool SupportsTarget (WorkspaceItem item, string target) - { - if (item is Solution) - return SupportsTarget ((Solution) item, target); - else - return GetNext (item).SupportsTarget ((IBuildTarget) item, target); - } - - public virtual bool SupportsExecute (IBuildTarget item) - { - if (item is SolutionEntityItem) - return SupportsExecute ((SolutionEntityItem)item); - else if (item is WorkspaceItem) - return SupportsExecute ((WorkspaceItem) item); - else - return GetNext (item).SupportsExecute (item); - } - - protected virtual bool SupportsExecute (SolutionEntityItem item) - { - return GetNext (item).SupportsExecute ((IBuildTarget) item); - } - - protected virtual bool SupportsExecute (Solution solution) - { - return GetNext (solution).SupportsExecute ((IBuildTarget) solution); - } - - protected virtual bool SupportsExecute (WorkspaceItem item) - { - if (item is Solution) - return SupportsExecute ((Solution) item); - else - return GetNext (item).SupportsExecute ((IBuildTarget) item); - } - - protected virtual void Clean (IProgressMonitor monitor, IBuildTarget item, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) - Clean (monitor, (SolutionEntityItem) item, configuration); - else if (item is WorkspaceItem) - Clean (monitor, (WorkspaceItem) item, configuration); - else - GetNext (item).RunTarget (monitor, item, ProjectService.CleanTarget, configuration); - } - - protected virtual void Clean (IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration) - { - GetNext (item).RunTarget (monitor, item, ProjectService.CleanTarget, configuration); - } - - protected virtual void Clean (IProgressMonitor monitor, Solution item, ConfigurationSelector configuration) - { - GetNext (item).RunTarget (monitor, item, ProjectService.CleanTarget, configuration); - } - - protected virtual void Clean (IProgressMonitor monitor, WorkspaceItem item, ConfigurationSelector configuration) - { - if (item is Solution) - Clean (monitor, (Solution) item, configuration); - else - GetNext (item).RunTarget (monitor, item, ProjectService.CleanTarget, configuration); - } - - protected virtual BuildResult Build (IProgressMonitor monitor, IBuildTarget item, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) - return Build (monitor, (SolutionEntityItem) item, configuration); - if (item is WorkspaceItem) - return Build (monitor, (WorkspaceItem) item, configuration); - return GetNext (item).RunTarget (monitor, item, ProjectService.BuildTarget, configuration); - } - - protected virtual BuildResult Build (IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration) - { - return GetNext (item).RunTarget (monitor, item, ProjectService.BuildTarget, configuration); - } - - protected virtual BuildResult Build (IProgressMonitor monitor, WorkspaceItem item, ConfigurationSelector configuration) - { - if (item is Solution) - return Build (monitor, (Solution) item, configuration); - return GetNext (item).RunTarget (monitor, item, ProjectService.BuildTarget, configuration); - } - - protected virtual BuildResult Build (IProgressMonitor monitor, Solution solution, ConfigurationSelector configuration) - { - return GetNext (solution).RunTarget (monitor, solution, ProjectService.BuildTarget, configuration); - } - - public virtual void Execute (IProgressMonitor monitor, IBuildTarget item, ExecutionContext context, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) - Execute (monitor, (SolutionEntityItem)item, context, configuration); - else if (item is WorkspaceItem) - Execute (monitor, (WorkspaceItem) item, context, configuration); - else - GetNext (item).Execute (monitor, item, context, configuration); - } - - protected virtual void Execute (IProgressMonitor monitor, SolutionEntityItem item, ExecutionContext context, ConfigurationSelector configuration) - { - GetNext (item).Execute (monitor, (IBuildTarget) item, context, configuration); - } - - protected virtual void Execute (IProgressMonitor monitor, Solution solution, ExecutionContext context, ConfigurationSelector configuration) - { - GetNext (solution).Execute (monitor, (IBuildTarget) solution, context, configuration); - } - - protected virtual void Execute (IProgressMonitor monitor, WorkspaceItem item, ExecutionContext context, ConfigurationSelector configuration) - { - if (item is Solution) - Execute (monitor, (Solution) item, context, configuration); - else - GetNext (item).Execute (monitor, (IBuildTarget) item, context, configuration); - } - - public virtual bool CanExecute (IBuildTarget item, ExecutionContext context, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) - return CanExecute ((SolutionEntityItem)item, context, configuration); - else if (item is WorkspaceItem) - return CanExecute ((WorkspaceItem) item, context, configuration); - else - return GetNext (item).CanExecute (item, context, configuration); - } - - protected virtual bool CanExecute (SolutionEntityItem item, ExecutionContext context, ConfigurationSelector configuration) - { - return GetNext (item).CanExecute ((IBuildTarget) item, context, configuration); - } - - protected virtual bool CanExecute (Solution solution, ExecutionContext context, ConfigurationSelector configuration) - { - return GetNext (solution).CanExecute ((IBuildTarget) solution, context, configuration); - } - - protected virtual bool CanExecute (WorkspaceItem item, ExecutionContext context, ConfigurationSelector configuration) - { - if (item is Solution) - return CanExecute ((Solution) item, context, configuration); - else - return GetNext (item).CanExecute ((IBuildTarget) item, context, configuration); - } - - public virtual IEnumerable<ExecutionTarget> GetExecutionTargets (IBuildTarget item, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) - return GetExecutionTargets ((SolutionEntityItem)item, configuration); - else if (item is WorkspaceItem) - return GetExecutionTargets ((WorkspaceItem) item, configuration); - else - return GetNext (item).GetExecutionTargets (item, configuration); - } - - protected virtual IEnumerable<ExecutionTarget> GetExecutionTargets (SolutionEntityItem item, ConfigurationSelector configuration) - { - return GetNext (item).GetExecutionTargets ((IBuildTarget) item, configuration); - } - - protected virtual IEnumerable<ExecutionTarget> GetExecutionTargets (Solution solution, ConfigurationSelector configuration) - { - return GetNext (solution).GetExecutionTargets ((IBuildTarget) solution, configuration); - } - - protected virtual IEnumerable<ExecutionTarget> GetExecutionTargets (WorkspaceItem item, ConfigurationSelector configuration) - { - if (item is Solution) - return GetExecutionTargets ((Solution) item, configuration); - else - return GetNext (item).GetExecutionTargets ((IBuildTarget) item, configuration); - } - - public virtual bool GetNeedsBuilding (IBuildTarget item, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) - return GetNeedsBuilding ((SolutionEntityItem) item, configuration); - if (item is WorkspaceItem) - return GetNeedsBuilding ((WorkspaceItem) item, configuration); - return GetNext (item).GetNeedsBuilding (item, configuration); - } - - protected virtual bool GetNeedsBuilding (SolutionEntityItem item, ConfigurationSelector configuration) - { - return GetNext (item).GetNeedsBuilding ((IBuildTarget) item, configuration); - } - - protected virtual bool GetNeedsBuilding (Solution item, ConfigurationSelector configuration) - { - return GetNext (item).GetNeedsBuilding ((IBuildTarget) item, configuration); - } - - protected virtual bool GetNeedsBuilding (WorkspaceItem item, ConfigurationSelector configuration) - { - if (item is Solution) - return GetNeedsBuilding ((Solution) item, configuration); - return GetNext (item).GetNeedsBuilding ((IBuildTarget) item, configuration); - } - - public virtual void SetNeedsBuilding (IBuildTarget item, bool val, ConfigurationSelector configuration) - { - if (item is SolutionEntityItem) - SetNeedsBuilding ((SolutionEntityItem) item, val, configuration); - else if (item is WorkspaceItem) - SetNeedsBuilding ((WorkspaceItem) item, val, configuration); - else - GetNext (item).SetNeedsBuilding (item, val, configuration); - } - - protected virtual void SetNeedsBuilding (SolutionEntityItem item, bool val, ConfigurationSelector configuration) - { - GetNext (item).SetNeedsBuilding ((IBuildTarget) item, val, configuration); - } - - protected virtual void SetNeedsBuilding (Solution item, bool val, ConfigurationSelector configuration) - { - GetNext (item).SetNeedsBuilding ((IBuildTarget) item, val, configuration); - } - - protected virtual void SetNeedsBuilding (WorkspaceItem item, bool val, ConfigurationSelector configuration) - { - if (item is Solution) - SetNeedsBuilding ((Solution) item, val, configuration); - else - GetNext (item).SetNeedsBuilding ((IBuildTarget) item, val, configuration); - } - - internal virtual BuildResult Compile (IProgressMonitor monitor, SolutionEntityItem item, BuildData buildData, ItemCompileCallback callback) - { - compileCallbackStack.Push (callback); - try { - BuildResult res = Compile (monitor, item, buildData); - return res; - } finally { - compileCallbackStack.Pop (); - } - } - - protected virtual BuildResult Compile (IProgressMonitor monitor, SolutionEntityItem item, BuildData buildData) - { - return GetNext (item).Compile (monitor, item, buildData, compileCallbackStack.Peek ()); - } - - public virtual IEnumerable<string> GetReferencedAssemblies (DotNetProject project, ConfigurationSelector configuration, bool includeProjectReferences) - { - return GetNext (project).GetReferencedAssemblies (project, configuration, includeProjectReferences); - } } public class BuildData @@ -405,16 +92,21 @@ namespace MonoDevelop.Projects public ConfigurationSelector ConfigurationSelector { get; internal set; } } - class UnknownItem: IBuildTarget + class UnknownItem: WorkspaceObject, IBuildTarget { public static UnknownItem Instance = new UnknownItem (); - - public BuildResult RunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) + + public Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector configuration, bool buildReferencedTargets = false) { - return new BuildResult (); + return Task.FromResult (BuildResult.Success); } - public void Execute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + public Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return Task.FromResult (BuildResult.Success); + } + + public Task Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { throw new System.NotImplementedException(); } @@ -424,45 +116,24 @@ namespace MonoDevelop.Projects return false; } - public bool SupportsTarget (string target) - { - return false; - } - public bool NeedsBuilding (ConfigurationSelector configuration) { return false; } - - public void SetNeedsBuilding (bool needsBuilding, ConfigurationSelector configuration) + + protected override string OnGetName () { + return "Unknown"; } - - public void Save (IProgressMonitor monitor) + + protected override string OnGetBaseDirectory () { + return FilePath.Empty; } - - public string Name { - get { return "Unknown"; } - set { } - } - - - public FilePath ItemDirectory { - get { return FilePath.Empty; } - } - - public FilePath BaseDirectory { - get { return FilePath.Empty; } - set { } - } - - public void Dispose () + + protected override string OnGetItemDirectory () { - } - - public System.Collections.IDictionary ExtendedProperties { - get { return null; } + return FilePath.Empty; } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterDotNetProject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterDotNetProject.cs new file mode 100644 index 0000000000..1d237ac31f --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterDotNetProject.cs @@ -0,0 +1,45 @@ +// +// RegisterDotNetProject.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 Mono.Addins; + +namespace MonoDevelop.Projects +{ + public class RegisterDotNetProjectTypeAttribute: RegisterProjectTypeAttribute + { + protected RegisterDotNetProjectTypeAttribute () + { + } + + public RegisterDotNetProjectTypeAttribute ([NodeAttribute ("guid")] string guid, [NodeAttribute("language")] string language): base (guid) + { + } + + [NodeAttribute ("language", Required=true)] + public string Language { get; set; } + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/PortableDotNetProjectBinding.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectAttribute.cs index 4ec770d696..e582055a24 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/PortableDotNetProjectBinding.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectAttribute.cs @@ -1,20 +1,21 @@ -// -// PortableDotNetProjectBinding.cs -// -// Author: Jeffrey Stedfast <jeff@xamarin.com> -// -// Copyright (c) 2012 Xamarin Inc. -// +// +// MSBuildProjectTypeAttribute.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 @@ -22,36 +23,23 @@ // 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.Xml; -using MonoDevelop.Core.Serialization; using MonoDevelop.Core; +using System.Threading.Tasks; +using MonoDevelop.Projects.Formats.MSBuild; +using Mono.Addins; namespace MonoDevelop.Projects { - public class PortableDotNetProjectBinding : IProjectBinding + public class RegisterProjectTypeAttribute: RegisterSolutionItemTypeAttribute { - public string Name { - get { return "PortableDotNet"; } - } - - public Project CreateProject (ProjectCreateInformation info, System.Xml.XmlElement projectOptions) - { - string languageName = projectOptions.GetAttribute ("language"); - - return new PortableDotNetProject (languageName, info, projectOptions); - } - - public Project CreateSingleFileProject (string sourceFile) + protected RegisterProjectTypeAttribute () { - throw new InvalidOperationException (); } - - public bool CanCreateSingleFileProject (string sourceFile) + + public RegisterProjectTypeAttribute ([NodeAttribute ("guid")] string guid): base (guid) { - return false; } } } + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectFlavorAttribute.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectFlavorAttribute.cs new file mode 100644 index 0000000000..023723f1db --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectFlavorAttribute.cs @@ -0,0 +1,48 @@ +// +// ProjectFlavorTypeAttribute.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 System.Linq; +using Mono.Addins; + +namespace MonoDevelop.Projects +{ + public class RegisterProjectFlavorAttribute: RegisterProjectModelExtensionAttribute + { + internal RegisterProjectFlavorAttribute () + { + } + + public RegisterProjectFlavorAttribute ([NodeAttribute ("guid")] string guid) + { + Guid = guid; + } + + [NodeAttribute ("guid", Description = "GUID of the extension. The extension will be loaded if the project has this GUID in the project type GUID list. " + + "If not specified, the extension will be applied to all projects.")] + public string Guid { get; set; } + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectModelExtensionAttribute.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectModelExtensionAttribute.cs new file mode 100644 index 0000000000..9c47679650 --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterProjectModelExtensionAttribute.cs @@ -0,0 +1,36 @@ +// +// RegisterProjectModelExtensionAttribute.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 Mono.Addins; + +namespace MonoDevelop.Projects +{ + public class RegisterProjectModelExtensionAttribute: CustomExtensionAttribute + { + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterSolutionItemTypeAttribute.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterSolutionItemTypeAttribute.cs new file mode 100644 index 0000000000..ccdc33ab8b --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/RegisterSolutionItemTypeAttribute.cs @@ -0,0 +1,62 @@ +// +// SolutionItemTypeAttribute.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 System.Threading.Tasks; +using MonoDevelop.Core; +using Mono.Addins; +using MonoDevelop.Core.ProgressMonitoring; + +namespace MonoDevelop.Projects +{ + public class RegisterSolutionItemTypeAttribute: CustomExtensionAttribute + { + [NodeAttribute ("guid", Required=true)] + public string Guid { get; set; } + + [NodeAttribute ("extension")] + public string Extension { get; set; } + + [NodeAttribute ("import")] + public string Import { get; set; } + + [NodeAttribute ("alias")] + public string Alias { get; set; } + + public string TypeName { + get { return ((TypeExtensionNode)ExtensionNode).TypeName; } + } + + protected RegisterSolutionItemTypeAttribute () + { + } + + public RegisterSolutionItemTypeAttribute ([NodeAttribute ("guid")] string guid) + { + Guid = guid; + } + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Solution.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Solution.cs index f0b7f171f2..97534bbc16 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Solution.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Solution.cs @@ -36,18 +36,21 @@ using MonoDevelop.Core; using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Core.StringParsing; using MonoDevelop.Projects.Policies; +using MonoDevelop.Core.Execution; +using System.Threading.Tasks; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { [ProjectModelDataItem] - public class Solution: WorkspaceItem, IConfigurationTarget, IPolicyProvider + public class Solution: WorkspaceItem, IConfigurationTarget, IPolicyProvider, IBuildTarget { internal object MemoryProbe = Counters.SolutionsInMemory.CreateMemoryProbe (); SolutionFolder rootFolder; string defaultConfiguration; - SolutionEntityItem startupItem; - List<SolutionEntityItem> startupItems; + SolutionItem startupItem; + List<SolutionItem> startupItems; bool singleStartup = true; // Used for serialization only @@ -70,8 +73,24 @@ namespace MonoDevelop.Projects { Counters.SolutionsLoaded++; configurations = new SolutionConfigurationCollection (this); + Initialize (this); } - + + internal HashSet<string> LoadedProjects { + get; + set; + } + + SolutionExtension itemExtension; + + SolutionExtension SolutionExtension { + get { + if (itemExtension == null) + itemExtension = ExtensionChain.GetExtension<SolutionExtension> (); + return itemExtension; + } + } + public SolutionFolder RootFolder { get { if (rootFolder == null) { @@ -103,18 +122,13 @@ namespace MonoDevelop.Projects // Does not include solution folders public ReadOnlyCollection<SolutionItem> Items { get { - if (solutionItems == null) { - List<SolutionItem> list = new List<SolutionItem> (); - foreach (SolutionItem item in GetAllSolutionItems ()) - if (!(item is SolutionFolder)) - list.Add (item); - solutionItems = list.AsReadOnly (); - } + if (solutionItems == null) + solutionItems = GetAllSolutionItems ().ToList().AsReadOnly (); return solutionItems; } } - public SolutionEntityItem StartupItem { + public SolutionItem StartupItem { get { if (startItemFileName != null) { startupItem = FindSolutionItem (startItemFileName); @@ -122,8 +136,8 @@ namespace MonoDevelop.Projects singleStartup = true; } if (startupItem == null && singleStartup) { - ReadOnlyCollection<SolutionEntityItem> its = GetAllSolutionItems<SolutionEntityItem> (); - if (its.Count > 0) + var its = GetAllItems<SolutionItem> (); + if (its.Any ()) startupItem = its.FirstOrDefault (it => it.SupportsExecute ()); } return startupItem; @@ -161,12 +175,12 @@ namespace MonoDevelop.Projects } } - public List<SolutionEntityItem> MultiStartupItems { + public List<SolutionItem> MultiStartupItems { get { if (multiStartupItems != null) { - startupItems = new List<SolutionEntityItem> (); + startupItems = new List<SolutionItem> (); foreach (string file in multiStartupItems) { - SolutionEntityItem it = FindSolutionItem (file); + SolutionItem it = FindSolutionItem (file); if (it != null) startupItems.Add (it); } @@ -174,7 +188,7 @@ namespace MonoDevelop.Projects singleStartup = false; } else if (startupItems == null) - startupItems = new List<SolutionEntityItem> (); + startupItems = new List<SolutionItem> (); return startupItems; } } @@ -200,7 +214,7 @@ namespace MonoDevelop.Projects if (multiStartupItems != null) return multiStartupItems; List<string> files = new List<string> (); - foreach (SolutionEntityItem item in MultiStartupItems) + foreach (SolutionItem item in MultiStartupItems) files.Add (item.FileName); return files; } @@ -248,30 +262,30 @@ namespace MonoDevelop.Projects CleanItemProperties (UserProperties, RootFolder, "MonoDevelop.Ide.ItemProperties"); } - void CollectItemProperties (PropertyBag props, SolutionItem item, string path) + void CollectItemProperties (PropertyBag props, SolutionFolderItem item, string path) { if (!item.UserProperties.IsEmpty && item.ParentFolder != null) props.SetValue (path, item.UserProperties); SolutionFolder sf = item as SolutionFolder; if (sf != null) { - foreach (SolutionItem ci in sf.Items) + foreach (SolutionFolderItem ci in sf.Items) CollectItemProperties (props, ci, path + "." + ci.Name); } } - void CleanItemProperties (PropertyBag props, SolutionItem item, string path) + void CleanItemProperties (PropertyBag props, SolutionFolderItem item, string path) { props.RemoveValue (path); SolutionFolder sf = item as SolutionFolder; if (sf != null) { - foreach (SolutionItem ci in sf.Items) + foreach (SolutionFolderItem ci in sf.Items) CleanItemProperties (props, ci, path + "." + ci.Name); } } - void LoadItemProperties (PropertyBag props, SolutionItem item, string path) + void LoadItemProperties (PropertyBag props, SolutionFolderItem item, string path) { PropertyBag info = props.GetValue<PropertyBag> (path); if (info != null) { @@ -281,14 +295,14 @@ namespace MonoDevelop.Projects SolutionFolder sf = item as SolutionFolder; if (sf != null) { - foreach (SolutionItem ci in sf.Items) + foreach (SolutionFolderItem ci in sf.Items) LoadItemProperties (props, ci, path + "." + ci.Name); } } public void CreateDefaultConfigurations () { - foreach (SolutionEntityItem item in Items.Where (it => it.SupportsBuild ())) { + foreach (SolutionItem item in Items.Where (it => it.SupportsBuild ())) { foreach (ItemConfiguration conf in item.Configurations) { SolutionConfiguration sc = Configurations [conf.Id]; if (sc == null) { @@ -308,7 +322,7 @@ namespace MonoDevelop.Projects public SolutionConfiguration AddConfiguration (string name, bool createConfigForItems) { SolutionConfiguration conf = new SolutionConfiguration (name); - foreach (SolutionEntityItem item in Items.Where (it => it.SupportsBuild())) { + foreach (SolutionItem item in Items.Where (it => it.SupportsBuild())) { if (createConfigForItems && item.GetConfiguration (new ItemConfigurationSelector (name)) == null) { SolutionItemConfiguration newc = item.CreateConfiguration (name); if (item.DefaultConfiguration != null) @@ -334,15 +348,15 @@ namespace MonoDevelop.Projects return (SolutionConfiguration) configuration.GetConfiguration (this) ?? DefaultConfiguration; } - public SolutionItem GetSolutionItem (string itemId) + public SolutionFolderItem GetSolutionItem (string itemId) { - foreach (SolutionItem item in Items) + foreach (SolutionFolderItem item in Items) if (item.ItemId == itemId) return item; return null; } - public override SolutionEntityItem FindSolutionItem (string fileName) + public SolutionItem FindSolutionItem (string fileName) { return RootFolder.FindSolutionItem (fileName); } @@ -352,11 +366,16 @@ namespace MonoDevelop.Projects return RootFolder.FindProjectByName (name); } - public override ReadOnlyCollection<T> GetAllSolutionItems<T> () + public IEnumerable<SolutionItem> GetAllSolutionItems () { - return RootFolder.GetAllItems<T> (); + return GetAllItems<SolutionItem> (); } - + + public IEnumerable<Project> GetAllProjects () + { + return GetAllItems<Project> (); + } + public ReadOnlyCollection<T> GetAllSolutionItemsWithTopologicalSort<T> (ConfigurationSelector configuration) where T: SolutionItem { return RootFolder.GetAllItemsWithTopologicalSort<T> (configuration); @@ -378,17 +397,22 @@ namespace MonoDevelop.Projects return RootFolder.GetProjectsContainingFile (fileName); } - public override bool ContainsItem (IWorkspaceObject obj) + public override bool ContainsItem (WorkspaceObject obj) { if (base.ContainsItem (obj)) return true; - foreach (SolutionItem it in GetAllSolutionItems<SolutionItem> ()) { + foreach (SolutionFolderItem it in GetAllItems<SolutionFolderItem> ()) { if (it == obj) return true; } return false; } + + protected override IEnumerable<WorkspaceObject> OnGetChildren () + { + yield return RootFolder; + } public string Description { get { @@ -494,7 +518,7 @@ namespace MonoDevelop.Projects } set { version = value; - foreach (SolutionEntityItem item in GetAllSolutionItems<SolutionEntityItem> ()) { + foreach (SolutionItem item in GetAllItems<SolutionItem> ()) { if (item.SyncVersionWithSolution) item.Version = value; } @@ -515,7 +539,7 @@ namespace MonoDevelop.Projects return list == null || !list.Contains (solutionItemPath); } - public void SetSolutionItemEnabled (string solutionItemPath, bool enabled) + internal void SetSolutionItemEnabled (string solutionItemPath, bool enabled) { solutionItemPath = GetRelativeChildPath (Path.GetFullPath (solutionItemPath)); var list = UserProperties.GetValue<List<string>> ("DisabledProjects"); @@ -543,25 +567,91 @@ namespace MonoDevelop.Projects } } } - - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + + + public Task<BuildResult> Clean (ProgressMonitor monitor, string configuration) + { + return Clean (monitor, (SolutionConfigurationSelector) configuration); + } + + public Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return SolutionExtension.Clean (monitor, configuration); + } + + public Task<BuildResult> Build (ProgressMonitor monitor, string configuration) + { + return SolutionExtension.Build (monitor, (SolutionConfigurationSelector) configuration); + } + + Task<BuildResult> IBuildTarget.Build (ProgressMonitor monitor, ConfigurationSelector configuration, bool buildReferencedTargets) + { + return Build (monitor, configuration); + } + + public Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return SolutionExtension.Build (monitor, configuration); + } + + public bool NeedsBuilding (ConfigurationSelector configuration) + { + return SolutionExtension.NeedsBuilding (configuration); + } + + public Task Execute (ProgressMonitor monitor, ExecutionContext context, string configuration) + { + return Execute (monitor, context, (SolutionConfigurationSelector) configuration); + } + + public Task Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + return SolutionExtension.Execute (monitor, context, configuration); + } + + public bool CanExecute (ExecutionContext context, string configuration) + { + return CanExecute (context, (SolutionConfigurationSelector) configuration); + } + + public bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + return SolutionExtension.CanExecute (context, configuration); + } + + public IEnumerable<ExecutionTarget> GetExecutionTargets (string configuration) + { + return GetExecutionTargets ((SolutionConfigurationSelector) configuration); + } + + public IEnumerable<ExecutionTarget> GetExecutionTargets (ConfigurationSelector configuration) + { + return SolutionExtension.GetExecutionTargets (this, configuration); + } + + protected virtual Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { return RootFolder.Build (monitor, configuration); } - - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) + + protected virtual bool OnGetNeedsBuilding (ConfigurationSelector configuration) + { + return RootFolder.NeedsBuilding (configuration); + } + + protected virtual Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) { - RootFolder.Clean (monitor, configuration); + return RootFolder.Clean (monitor, configuration); } - protected internal override bool OnGetCanExecute(ExecutionContext context, ConfigurationSelector configuration) + protected virtual bool OnGetCanExecute(ExecutionContext context, ConfigurationSelector configuration) { if (SingleStartup) { if (StartupItem == null) return false; return StartupItem.CanExecute (context, configuration); } else { - foreach (SolutionEntityItem it in MultiStartupItems) { + foreach (SolutionItem it in MultiStartupItems) { if (it.CanExecute (context, configuration)) return true; } @@ -569,44 +659,36 @@ namespace MonoDevelop.Projects } } - protected internal override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + protected async virtual Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { if (SingleStartup) { if (StartupItem == null) { monitor.ReportError (GettextCatalog.GetString ("Startup item not set"), null); return; } - StartupItem.Execute (monitor, context, configuration); + await StartupItem.Execute (monitor, context, configuration); } else { - List<IAsyncOperation> list = new List<IAsyncOperation> (); + var tasks = new List<Task> (); + var monitors = new List<AggregatedProgressMonitor> (); monitor.BeginTask ("Executing projects", 1); - SynchronizedProgressMonitor syncMonitor = new SynchronizedProgressMonitor (monitor); - - foreach (SolutionEntityItem it in MultiStartupItems) { + foreach (SolutionItem it in MultiStartupItems) { if (!it.CanExecute (context, configuration)) continue; AggregatedProgressMonitor mon = new AggregatedProgressMonitor (); - mon.AddSlaveMonitor (syncMonitor, MonitorAction.ReportError | MonitorAction.ReportWarning | MonitorAction.SlaveCancel); - list.Add (mon.AsyncOperation); - SolutionEntityItem cit = it; - - Thread t = new Thread (delegate () { - try { - using (mon) { - cit.Execute (mon, context, configuration); - } - } catch (Exception ex) { - LoggingService.LogError ("Project execution failed", ex); - } - }); - t.Name = "Project execution"; - t.IsBackground = true; - t.Start (); + mon.AddSlaveMonitor (monitor, MonitorAction.ReportError | MonitorAction.ReportWarning | MonitorAction.SlaveCancel); + monitors.Add (mon); + tasks.Add (it.Execute (mon, context, configuration)); } - foreach (IAsyncOperation op in list) - op.WaitForCompleted (); - + try { + await Task.WhenAll (tasks); + } catch (Exception ex) { + LoggingService.LogError ("Project execution failed", ex); + } finally { + foreach (var m in monitors) + m.Dispose (); + } + monitor.EndTask (); } } @@ -617,25 +699,25 @@ namespace MonoDevelop.Projects StartupItemChanged (this, e); } - public override void ConvertToFormat (FileFormat format, bool convertChildren) + public async override Task ConvertToFormat (FileFormat format, bool convertChildren) { - base.ConvertToFormat (format, convertChildren); - foreach (SolutionItem item in GetAllSolutionItems<SolutionItem> ()) - ConvertToSolutionFormat (item, convertChildren); + await base.ConvertToFormat (format, convertChildren); + foreach (SolutionFolderItem item in GetAllItems<SolutionFolderItem> ()) + await ConvertToSolutionFormat (item, convertChildren); } public override bool SupportsFormat (FileFormat format) { if (!base.SupportsFormat (format)) return false; - return GetAllSolutionItems<SolutionEntityItem> ().All (p => p.SupportsFormat (format)); + return GetAllItems<SolutionItem> ().All (p => p.SupportsFormat (format)); }
- public override List<FilePath> GetItemFiles (bool includeReferencedFiles) + protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) {
- List<FilePath> files = base.GetItemFiles (includeReferencedFiles); + List<FilePath> files = base.OnGetItemFiles (includeReferencedFiles).ToList (); if (includeReferencedFiles) { - foreach (SolutionEntityItem item in GetAllSolutionItems<SolutionEntityItem> ()) + foreach (SolutionItem item in GetAllItems<SolutionItem> ()) files.AddRange (item.GetItemFiles (true)); } return files; @@ -649,7 +731,7 @@ namespace MonoDevelop.Projects SolutionFolder sf = args.SolutionItem as SolutionFolder; if (sf != null) { - foreach (SolutionItem eitem in sf.GetAllItems<SolutionItem> ()) + foreach (SolutionFolderItem eitem in sf.GetAllItems<SolutionFolderItem> ()) SetupNewItem (eitem, null); } else { @@ -660,14 +742,14 @@ namespace MonoDevelop.Projects SolutionItemAdded (this, args); } - void SetupNewItem (SolutionItem item, SolutionItem replacedItem) + void SetupNewItem (SolutionFolderItem item, SolutionFolderItem replacedItem) { - ConvertToSolutionFormat (item, false); + ConvertToSolutionFormat (item, false).Wait (); - SolutionEntityItem eitem = item as SolutionEntityItem; + SolutionItem eitem = item as SolutionItem; if (eitem != null) { eitem.NeedsReload = false; - if (eitem.SupportsBuild () || replacedItem != null) { + if (eitem.SupportsConfigurations () || replacedItem != null) { if (replacedItem == null) { // Register the new entry in every solution configuration foreach (SolutionConfiguration conf in Configurations) @@ -678,11 +760,11 @@ namespace MonoDevelop.Projects } else { // Reuse the configuration information of the replaced item foreach (SolutionConfiguration conf in Configurations) - conf.ReplaceItem ((SolutionEntityItem)replacedItem, eitem); + conf.ReplaceItem ((SolutionItem)replacedItem, eitem); if (StartupItem == replacedItem) StartupItem = eitem; else { - int i = MultiStartupItems.IndexOf ((SolutionEntityItem)replacedItem); + int i = MultiStartupItems.IndexOf ((SolutionItem)replacedItem); if (i != -1) MultiStartupItems [i] = eitem; } @@ -691,11 +773,11 @@ namespace MonoDevelop.Projects } } - void ConvertToSolutionFormat (SolutionItem item, bool force) + async Task ConvertToSolutionFormat (SolutionFolderItem item, bool force) { - SolutionEntityItem eitem = item as SolutionEntityItem; + SolutionItem eitem = item as SolutionItem; if (force || !FileFormat.Format.SupportsMixedFormats || eitem == null || !eitem.IsSaved) { - this.FileFormat.Format.ConvertToFormat (item); + await this.FileFormat.Format.ConvertToFormat (item); if (eitem != null) eitem.InstallFormat (this.FileFormat); } @@ -707,11 +789,11 @@ namespace MonoDevelop.Projects SolutionFolder sf = args.SolutionItem as SolutionFolder; if (sf != null) { - foreach (SolutionEntityItem eitem in sf.GetAllItems<SolutionEntityItem> ()) + foreach (SolutionItem eitem in sf.GetAllItems<SolutionItem> ()) DetachItem (eitem, args.Reloading); } else { - SolutionEntityItem item = args.SolutionItem as SolutionEntityItem; + SolutionItem item = args.SolutionItem as SolutionItem; if (item != null) DetachItem (item, args.Reloading); } @@ -720,7 +802,7 @@ namespace MonoDevelop.Projects SolutionItemRemoved (this, args); } - void DetachItem (SolutionEntityItem item, bool reloading) + void DetachItem (SolutionItem item, bool reloading) { item.NeedsReload = false; if (!reloading) { @@ -744,7 +826,7 @@ namespace MonoDevelop.Projects if (projectToRemove == null) return; - foreach (DotNetProject project in GetAllSolutionItems <DotNetProject>()) { + foreach (DotNetProject project in GetAllItems <DotNetProject>()) { if (project == projectToRemove) continue; @@ -760,7 +842,27 @@ namespace MonoDevelop.Projects } } } + + internal void ReadSolution (ProgressMonitor monitor, SlnFile file) + { + SolutionExtension.OnReadSolution (monitor, file); + } + + protected virtual void OnReadSolution (ProgressMonitor monitor, SlnFile file) + { + ((MSBuildFileFormat)FileFormat.Format).SlnFileFormat.LoadSolution (this, file, monitor); + } + + internal void WriteSolution (ProgressMonitor monitor, SlnFile file) + { + SolutionExtension.OnWriteSolution (monitor, file); + } + protected virtual void OnWriteSolution (ProgressMonitor monitor, SlnFile file) + { + ((MSBuildFileFormat)FileFormat.Format).SlnFileFormat.WriteFileInternal (file, this, monitor); + } + internal void NotifyConfigurationsChanged () { OnConfigurationsChanged (); @@ -843,6 +945,54 @@ namespace MonoDevelop.Projects public event SolutionItemModifiedEventHandler EntryModified; public event SolutionItemEventHandler EntrySaved; public event EventHandler<SolutionItemEventArgs> ItemReloadRequired; + + protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions () + { + return base.CreateDefaultExtensions ().Concat (Enumerable.Repeat (new DefaultSolutionExtension (), 1)); + } + + internal class DefaultSolutionExtension: SolutionExtension + { + internal protected override IEnumerable<FilePath> GetItemFiles (bool includeReferencedFiles) + { + return Solution.OnGetItemFiles (includeReferencedFiles); + } + + internal protected override Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return Solution.OnBuild (monitor, configuration); + } + + internal protected override bool NeedsBuilding (ConfigurationSelector configuration) + { + return Solution.OnGetNeedsBuilding (configuration); + } + + internal protected override Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return Solution.OnClean (monitor, configuration); + } + + internal protected override Task Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + return Solution.OnExecute (monitor, context, configuration); + } + + internal protected override bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + return Solution.OnGetCanExecute (context, configuration); + } + + internal protected override void OnReadSolution (ProgressMonitor monitor, SlnFile file) + { + Solution.OnReadSolution (monitor, file); + } + + internal protected override void OnWriteSolution (ProgressMonitor monitor, SlnFile file) + { + Solution.OnWriteSolution (monitor, file); + } + } } [Mono.Addins.Extension] diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfiguration.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfiguration.cs index dfa4bc6832..717edf5f9b 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfiguration.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfiguration.cs @@ -73,7 +73,7 @@ namespace MonoDevelop.Projects get { return configurations.AsReadOnly (); } } - public bool BuildEnabledForItem (SolutionEntityItem item) + public bool BuildEnabledForItem (SolutionItem item) { foreach (SolutionConfigurationEntry entry in configurations) { if (entry.Item == item) @@ -82,7 +82,7 @@ namespace MonoDevelop.Projects return false; } - public string GetMappedConfiguration (SolutionEntityItem item) + public string GetMappedConfiguration (SolutionItem item) { foreach (SolutionConfigurationEntry entry in configurations) { if (entry.Item == item) @@ -91,7 +91,7 @@ namespace MonoDevelop.Projects return null; } - public SolutionConfigurationEntry GetEntryForItem (SolutionEntityItem item) + public SolutionConfigurationEntry GetEntryForItem (SolutionItem item) { foreach (SolutionConfigurationEntry entry in configurations) { if (entry.Item == item) @@ -100,13 +100,13 @@ namespace MonoDevelop.Projects return null; } - public SolutionConfigurationEntry AddItem (SolutionEntityItem item) + public SolutionConfigurationEntry AddItem (SolutionItem item) { string conf = FindMatchingConfiguration (item); return AddItem (item, conf != null, conf); } - string FindMatchingConfiguration (SolutionEntityItem item) + string FindMatchingConfiguration (SolutionItem item) { SolutionItemConfiguration startupConfiguration = null; @@ -153,7 +153,7 @@ namespace MonoDevelop.Projects return item.Configurations [0].Id; } - public SolutionConfigurationEntry AddItem (SolutionEntityItem item, bool build, string itemConfiguration) + public SolutionConfigurationEntry AddItem (SolutionItem item, bool build, string itemConfiguration) { if (itemConfiguration == null) itemConfiguration = Name; @@ -166,7 +166,7 @@ namespace MonoDevelop.Projects return conf; } - public void RemoveItem (SolutionEntityItem item) + public void RemoveItem (SolutionItem item) { for (int n=0; n<configurations.Count; n++) { if (configurations [n].Item == item) { @@ -176,7 +176,7 @@ namespace MonoDevelop.Projects } } - internal void ReplaceItem (SolutionEntityItem oldItem, SolutionEntityItem newItem) + internal void ReplaceItem (SolutionItem oldItem, SolutionItem newItem) { foreach (var e in configurations.Where (ce => ce.Item == oldItem)) e.Item = newItem; @@ -203,7 +203,7 @@ namespace MonoDevelop.Projects public class SolutionConfigurationEntry { - SolutionEntityItem item; + SolutionItem item; SolutionConfiguration parentConfig; [ItemProperty ("name")] @@ -227,7 +227,7 @@ namespace MonoDevelop.Projects this.deploy = other.deploy; } - internal SolutionConfigurationEntry (SolutionConfiguration parentConfig, SolutionEntityItem item) + internal SolutionConfigurationEntry (SolutionConfiguration parentConfig, SolutionItem item) { this.parentConfig = parentConfig; this.item = item; @@ -258,12 +258,12 @@ namespace MonoDevelop.Projects set { deploy = value; } } - public SolutionEntityItem Item { + public SolutionItem Item { get { if (item == null && parentConfig != null) { Solution sol = parentConfig.ParentSolution; if (sol != null) - item = sol.GetSolutionItem (itemId) as SolutionEntityItem; + item = sol.GetSolutionItem (itemId) as SolutionItem; } return item; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfigurationSelector.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfigurationSelector.cs index 04beb91589..531bd74947 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfigurationSelector.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionConfigurationSelector.cs @@ -48,9 +48,9 @@ namespace MonoDevelop.Projects public override ItemConfiguration GetConfiguration (IConfigurationTarget target) { ItemConfiguration sconf; - if (target is SolutionEntityItem) { + if (target is SolutionItem) { // Get the mapped configuration - SolutionEntityItem item = (SolutionEntityItem) target; + SolutionItem item = (SolutionItem) target; if (item.ParentSolution != null) { SolutionConfiguration config = item.ParentSolution.Configurations [Id]; if (config != null) { diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionEntityItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionEntityItem.cs deleted file mode 100644 index 0698a3fcf3..0000000000 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionEntityItem.cs +++ /dev/null @@ -1,584 +0,0 @@ -// SolutionEntityItem.cs -// -// Author: -// Lluis Sanchez Gual <lluis@novell.com> -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.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 System.Xml; -using System.IO; -using System.Collections; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Collections.Generic; -using System.Reflection; -using System.Diagnostics; -using System.CodeDom.Compiler; - -using MonoDevelop.Core; -using MonoDevelop.Projects; -using MonoDevelop.Core.Serialization; -using MonoDevelop.Projects.Extensions; -using MonoDevelop.Core.StringParsing; - -namespace MonoDevelop.Projects -{ - [ProjectModelDataItem (FallbackType = typeof(UnknownSolutionItem))] - public abstract class SolutionEntityItem : SolutionItem, IConfigurationTarget, IWorkspaceFileObject - { - internal object MemoryProbe = Counters.ItemsInMemory.CreateMemoryProbe (); - - ProjectItemCollection items; - ProjectItemCollection wildcardItems; - ItemCollection<SolutionEntityItem> dependencies = new ItemCollection<SolutionEntityItem> (); - - SolutionItemEventArgs thisItemArgs; - - FileStatusTracker<SolutionItemEventArgs> fileStatusTracker; - - FilePath fileName; - string name; - - FileFormat fileFormat; - - SolutionItemConfiguration activeConfiguration; - SolutionItemConfigurationCollection configurations; - - public event EventHandler ConfigurationsChanged; - public event ConfigurationEventHandler DefaultConfigurationChanged; - public event ConfigurationEventHandler ConfigurationAdded; - public event ConfigurationEventHandler ConfigurationRemoved; - public event EventHandler<ProjectItemEventArgs> ProjectItemAdded; - public event EventHandler<ProjectItemEventArgs> ProjectItemRemoved; - - public SolutionEntityItem () - { - items = new ProjectItemCollection (this); - wildcardItems = new ProjectItemCollection (this); - thisItemArgs = new SolutionItemEventArgs (this); - configurations = new SolutionItemConfigurationCollection (this); - configurations.ConfigurationAdded += new ConfigurationEventHandler (OnConfigurationAddedToCollection); - configurations.ConfigurationRemoved += new ConfigurationEventHandler (OnConfigurationRemovedFromCollection); - Counters.ItemsLoaded++; - fileStatusTracker = new FileStatusTracker<SolutionItemEventArgs> (this, OnReloadRequired, new SolutionItemEventArgs (this)); - } - - public override void Dispose () - { - if (Disposed) - return; - - Counters.ItemsLoaded--; - - foreach (var item in items.Concat (wildcardItems)) { - IDisposable disp = item as IDisposable; - if (disp != null) - disp.Dispose (); - } - - // items = null; - // wildcardItems = null; - // thisItemArgs = null; - // fileStatusTracker = null; - // fileFormat = null; - // activeConfiguration = null; - // configurations = null; - - base.Dispose (); - } - - - internal override void SetItemHandler (ISolutionItemHandler handler) - { - string oldName = Name; - string oldFile = FileName; - - base.SetItemHandler (handler); - - // This will update the name if needed, when SyncFileName is true - Name = oldName; - if (!string.IsNullOrEmpty (oldFile)) - FileName = oldFile; - } - - [ItemProperty ("ReleaseVersion", DefaultValue="0.1")] - string releaseVersion = "0.1"; - - [ItemProperty ("SynchReleaseVersion", DefaultValue = true)] - bool syncReleaseVersion = true; - - public string Version { - get { - // If syncReleaseVersion is set, releaseVersion will already contain the solution's version - // That's because the version must be up to date even when loading the project individually - return releaseVersion; - } - set { - releaseVersion = value; - NotifyModified ("Version"); - } - } - - public bool SyncVersionWithSolution { - get { - return syncReleaseVersion; - } - set { - syncReleaseVersion = value; - if (syncReleaseVersion && ParentSolution != null) - Version = ParentSolution.Version; - NotifyModified ("SyncVersionWithSolution"); - } - } - - [ItemProperty ("name")] - public override string Name { - get { - return name ?? string.Empty; - } - set { - if (name == value) - return; - string oldName = name; - name = value; - if (!Loading && ItemHandler.SyncFileName) { - if (string.IsNullOrEmpty (fileName)) - FileName = value; - else { - string ext = fileName.Extension; - FileName = fileName.ParentDirectory.Combine (value) + ext; - } - } - OnNameChanged (new SolutionItemRenamedEventArgs (this, oldName, name)); - } - } - - public virtual FilePath FileName { - get { - return fileName; - } - set { - fileName = value; - if (FileFormat != null) - fileName = FileFormat.GetValidFileName (this, fileName); - if (ItemHandler.SyncFileName) - Name = fileName.FileNameWithoutExtension; - NotifyModified ("FileName"); - } - } - - public bool Enabled { - get { return ParentSolution != null ? ParentSolution.IsSolutionItemEnabled (FileName) : true; } - set { - if (ParentSolution != null) - ParentSolution.SetSolutionItemEnabled (FileName, value); - } - } - - public FileFormat FileFormat { - get { - if (ParentSolution != null) { - if (ParentSolution.FileFormat.Format.SupportsMixedFormats && fileFormat != null) - return fileFormat; - return ParentSolution.FileFormat; - } - if (fileFormat == null) - fileFormat = Services.ProjectService.GetDefaultFormat (this); - return fileFormat; - } - set { - if (ParentSolution != null && !ParentSolution.FileFormat.Format.SupportsMixedFormats) - throw new InvalidOperationException ("The file format can't be changed when the item belongs to a solution."); - InstallFormat (value); - fileFormat.Format.ConvertToFormat (this); - NeedsReload = false; - NotifyModified ("FileFormat"); - } - } - - public ProjectItemCollection Items { - get { return items; } - } - - internal ProjectItemCollection WildcardItems { - get { return wildcardItems; } - } - - /// <summary> - /// Projects that need to be built before building this one - /// </summary> - /// <value>The dependencies.</value> - public ItemCollection<SolutionEntityItem> ItemDependencies { - get { return dependencies; } - } - - public override IEnumerable<SolutionItem> GetReferencedItems (ConfigurationSelector configuration) - { - return base.GetReferencedItems (configuration).Concat (dependencies); - } - - void IWorkspaceFileObject.ConvertToFormat (FileFormat format, bool convertChildren) - { - this.FileFormat = format; - } - - public virtual bool SupportsFormat (FileFormat format) - { - return true; - } - - internal void InstallFormat (FileFormat format) - { - fileFormat = format; - if (fileName != FilePath.Null) - fileName = fileFormat.GetValidFileName (this, fileName); - } - - protected override void InitializeItemHandler () - { - Services.ProjectService.GetDefaultFormat (this).Format.ConvertToFormat (this); - } - - protected override FilePath GetDefaultBaseDirectory ( ) - { - return FileName.IsNullOrEmpty ? FilePath.Empty : FileName.ParentDirectory; - } - - public void Save (FilePath fileName, IProgressMonitor monitor) - { - FileName = fileName; - Save (monitor); - } - - public override void Save (IProgressMonitor monitor) - { - if (string.IsNullOrEmpty (FileName)) - throw new InvalidOperationException ("Project does not have a file name"); - - try { - fileStatusTracker.BeginSave (); - Services.ProjectService.GetExtensionChain (this).Save (monitor, this); - OnSaved (thisItemArgs); - } finally { - fileStatusTracker.EndSave (); - } - FileService.NotifyFileChanged (FileName); - } - - protected override void OnEndLoad () - { - base.OnEndLoad (); - fileStatusTracker.ResetLoadTimes (); - - if (syncReleaseVersion && ParentSolution != null) - releaseVersion = ParentSolution.Version; - } - - - internal bool IsSaved { - get { - return !string.IsNullOrEmpty (FileName) && File.Exists (FileName); - } - } - - public override bool NeedsReload { - get { return fileStatusTracker.NeedsReload; } - set { fileStatusTracker.NeedsReload = value; } - } - - public virtual bool ItemFilesChanged { - get { return fileStatusTracker.ItemFilesChanged; } - } - - internal protected override BuildResult OnRunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) - { - if (target == ProjectService.BuildTarget) { - SolutionItemConfiguration conf = GetConfiguration (configuration) as SolutionItemConfiguration; - if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Build)) { - conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Build, configuration); - return new BuildResult (); - } - } else if (target == ProjectService.CleanTarget) { - SolutionItemConfiguration config = GetConfiguration (configuration) as SolutionItemConfiguration; - if (config != null && config.CustomCommands.HasCommands (CustomCommandType.Clean)) { - config.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Clean, configuration); - return new BuildResult (); - } - } - return base.OnRunTarget (monitor, target, configuration); - } - - protected internal virtual void OnSave (IProgressMonitor monitor) - { - ItemHandler.Save (monitor); - } - - [Obsolete ("This method will be removed in future releases")] - public void SetNeedsBuilding (bool value) - { - // Nothing to be done - } - - public FilePath GetAbsoluteChildPath (FilePath relPath) - { - return relPath.ToAbsolute (BaseDirectory); - } - - public FilePath GetRelativeChildPath (FilePath absPath) - { - return absPath.ToRelative (BaseDirectory); - } - - public List<FilePath> GetItemFiles (bool includeReferencedFiles) - { - return Services.ProjectService.GetExtensionChain (this).GetItemFiles (this, includeReferencedFiles); - } - - internal protected virtual List<FilePath> OnGetItemFiles (bool includeReferencedFiles) - { - List<FilePath> col = FileFormat.Format.GetItemFiles (this); - if (!string.IsNullOrEmpty (FileName) && !col.Contains (FileName)) - col.Add (FileName); - return col; - } - - protected override void OnNameChanged (SolutionItemRenamedEventArgs e) - { - Solution solution = this.ParentSolution; - - if (solution != null) { - foreach (DotNetProject project in solution.GetAllSolutionItems<DotNetProject>()) { - if (project == this) - continue; - - project.RenameReferences (e.OldName, e.NewName); - } - } - fileStatusTracker.ResetLoadTimes (); - base.OnNameChanged (e); - } - - protected virtual void OnSaved (SolutionItemEventArgs args) - { - if (Saved != null) - Saved (this, args); - } - - public virtual string[] SupportedPlatforms { - get { - return new string [0]; - } - } - - public virtual SolutionItemConfiguration GetConfiguration (ConfigurationSelector configuration) - { - return (SolutionItemConfiguration) configuration.GetConfiguration (this) ?? DefaultConfiguration; - } - - ItemConfiguration IConfigurationTarget.DefaultConfiguration { - get { return DefaultConfiguration; } - set { DefaultConfiguration = (SolutionItemConfiguration) value; } - } - - public SolutionItemConfiguration DefaultConfiguration { - get { - if (activeConfiguration == null && configurations.Count > 0) { - return configurations[0]; - } - return activeConfiguration; - } - set { - if (activeConfiguration != value) { - activeConfiguration = value; - NotifyModified ("DefaultConfiguration"); - OnDefaultConfigurationChanged (new ConfigurationEventArgs (this, value)); - } - } - } - - public string DefaultConfigurationId { - get { - if (DefaultConfiguration != null) - return DefaultConfiguration.Id; - else - return null; - } - set { - DefaultConfiguration = GetConfiguration (new ItemConfigurationSelector (value)); - } - } - - public virtual ReadOnlyCollection<string> GetConfigurations () - { - List<string> configs = new List<string> (); - foreach (SolutionItemConfiguration conf in Configurations) - configs.Add (conf.Id); - return configs.AsReadOnly (); - } - - [ItemProperty ("Configurations")] - [ItemProperty ("Configuration", ValueType=typeof(SolutionItemConfiguration), Scope="*")] - public SolutionItemConfigurationCollection Configurations { - get { - return configurations; - } - } - - IItemConfigurationCollection IConfigurationTarget.Configurations { - get { - return Configurations; - } - } - - public SolutionItemConfiguration AddNewConfiguration (string name) - { - SolutionItemConfiguration config = CreateConfiguration (name); - Configurations.Add (config); - return config; - } - - ItemConfiguration IConfigurationTarget.CreateConfiguration (string name) - { - return CreateConfiguration (name); - } - - public virtual SolutionItemConfiguration CreateConfiguration (string name) - { - return new SolutionItemConfiguration (name); - } - - void OnConfigurationAddedToCollection (object ob, ConfigurationEventArgs args) - { - NotifyModified ("Configurations"); - OnConfigurationAdded (new ConfigurationEventArgs (this, args.Configuration)); - if (ConfigurationsChanged != null) - ConfigurationsChanged (this, EventArgs.Empty); - if (activeConfiguration == null) - DefaultConfigurationId = args.Configuration.Id; - } - - void OnConfigurationRemovedFromCollection (object ob, ConfigurationEventArgs args) - { - if (activeConfiguration == args.Configuration) { - if (Configurations.Count > 0) - DefaultConfiguration = Configurations [0]; - else - DefaultConfiguration = null; - } - NotifyModified ("Configurations"); - OnConfigurationRemoved (new ConfigurationEventArgs (this, args.Configuration)); - if (ConfigurationsChanged != null) - ConfigurationsChanged (this, EventArgs.Empty); - } - - public override StringTagModelDescription GetStringTagModelDescription (ConfigurationSelector conf) - { - StringTagModelDescription model = base.GetStringTagModelDescription (conf); - SolutionItemConfiguration config = GetConfiguration (conf); - if (config != null) - model.Add (config.GetType ()); - else - model.Add (typeof(SolutionItemConfiguration)); - return model; - } - - public override StringTagModel GetStringTagModel (ConfigurationSelector conf) - { - StringTagModel source = base.GetStringTagModel (conf); - SolutionItemConfiguration config = GetConfiguration (conf); - if (config != null) - source.Add (config); - return source; - } - - internal protected virtual void OnItemsAdded (IEnumerable<ProjectItem> objs) - { - NotifyModified ("Items"); - var args = new ProjectItemEventArgs (); - args.AddRange (objs.Select (pi => new ProjectItemEventInfo (this, pi))); - if (ProjectItemAdded != null) - ProjectItemAdded (this, args); - } - - internal protected virtual void OnItemsRemoved (IEnumerable<ProjectItem> objs) - { - NotifyModified ("Items"); - var args = new ProjectItemEventArgs (); - args.AddRange (objs.Select (pi => new ProjectItemEventInfo (this, pi))); - if (ProjectItemRemoved != null) - ProjectItemRemoved (this, args); - } - - protected virtual void OnDefaultConfigurationChanged (ConfigurationEventArgs args) - { - if (DefaultConfigurationChanged != null) - DefaultConfigurationChanged (this, args); - } - - protected virtual void OnConfigurationAdded (ConfigurationEventArgs args) - { - if (ConfigurationAdded != null) - ConfigurationAdded (this, args); - } - - protected virtual void OnConfigurationRemoved (ConfigurationEventArgs args) - { - if (ConfigurationRemoved != null) - ConfigurationRemoved (this, args); - } - - protected virtual void OnReloadRequired (SolutionItemEventArgs args) - { - fileStatusTracker.FireReloadRequired (args); - } - - public event SolutionItemEventHandler Saved; - -/* public event EventHandler<SolutionItemEventArgs> ReloadRequired { - add { fileStatusTracker.ReloadRequired += value; } - remove { fileStatusTracker.ReloadRequired -= value; } - } -*/ } - - [Mono.Addins.Extension] - class SolutionEntityItemTagProvider: StringTagProvider<SolutionEntityItem>, IStringTagProvider - { - public override IEnumerable<StringTagDescription> GetTags () - { - yield return new StringTagDescription ("ProjectFile", "Project File"); - } - - public override object GetTagValue (SolutionEntityItem item, string tag) - { - switch (tag) { - case "ITEMFILE": - case "PROJECTFILE": - case "PROJECTFILENAME": - return item.FileName; - } - throw new NotSupportedException (); - } - } -} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionExtension.cs new file mode 100644 index 0000000000..4da2bdf7d0 --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionExtension.cs @@ -0,0 +1,89 @@ +// +// SolutionExtension.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.Core; +using MonoDevelop.Core.Execution; +using System.Collections.Generic; +using System.Threading.Tasks; +using MonoDevelop.Projects.Formats.MSBuild; + +namespace MonoDevelop.Projects +{ + public class SolutionExtension: WorkspaceItemExtension + { + SolutionExtension next; + + protected Solution Solution { + get { return (Solution) base.Item; } + } + + internal protected override bool SupportsItem (WorkspaceItem item) + { + return item is Solution; + } + + internal protected virtual Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return next.Build (monitor, configuration); + } + + internal protected virtual Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return next.Clean (monitor, configuration); + } + + internal protected virtual Task Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + return next.Execute (monitor, context, configuration); + } + + internal protected virtual bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + return next.CanExecute (context, configuration); + } + + internal protected virtual IEnumerable<ExecutionTarget> GetExecutionTargets (Solution solution, ConfigurationSelector configuration) + { + return next.GetExecutionTargets (solution, configuration); + } + + internal protected virtual bool NeedsBuilding (ConfigurationSelector configuration) + { + return next.NeedsBuilding (configuration); + } + + internal protected virtual void OnReadSolution (ProgressMonitor monitor, SlnFile file) + { + next.OnReadSolution (monitor, file); + } + + internal protected virtual void OnWriteSolution (ProgressMonitor monitor, SlnFile file) + { + next.OnWriteSolution (monitor, file); + } + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolder.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolder.cs index d4f9cb7e91..15942ba39c 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolder.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolder.cs @@ -45,11 +45,12 @@ using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Projects; using MonoDevelop.Projects.Extensions; using MonoDevelop.Core.Serialization; +using System.Threading.Tasks; namespace MonoDevelop.Projects { [DataInclude (typeof(SolutionConfiguration))] - public class SolutionFolder : SolutionItem + public class SolutionFolder : SolutionFolderItem { SolutionFolderItemCollection items; SolutionFolderFileCollection files; @@ -67,6 +68,11 @@ namespace MonoDevelop.Projects } } + protected override IEnumerable<WorkspaceObject> OnGetChildren () + { + return Items; + } + internal SolutionFolderItemCollection GetItemsWithoutCreating () { return items; @@ -86,20 +92,17 @@ namespace MonoDevelop.Projects get { return ParentFolder == null; } } - public override string Name { - get { - if (ParentFolder == null && ParentSolution != null) - return ParentSolution.Name; - else - return name; - } - set { - if (value != name) { - string oldName = name; - name = value; - OnNameChanged (new SolutionItemRenamedEventArgs (this, oldName, name)); - } - } + protected override string OnGetName () + { + if (ParentFolder == null && ParentSolution != null) + return ParentSolution.Name; + else + return name; + } + + protected override void OnSetName (string value) + { + name = value; }
protected override FilePath GetDefaultBaseDirectory ( ) @@ -136,7 +139,7 @@ namespace MonoDevelop.Projects {
FilePath path = null; - foreach (SolutionItem it in Items) {
+ foreach (SolutionFolderItem it in Items) {
FilePath subdir; if (it is SolutionFolder) { SolutionFolder sf = (SolutionFolder) it; @@ -184,25 +187,19 @@ namespace MonoDevelop.Projects else return null; } - - internal override IDictionary InternalGetExtendedProperties { - get { - if (ParentSolution != null && ParentFolder == null) - return ParentSolution.ExtendedProperties; - else - return base.InternalGetExtendedProperties; - } - } - - protected override void InitializeItemHandler () + + protected override IDictionary OnGetExtendedProperties () { - SetItemHandler (new DummySolutionFolderHandler (this)); + if (ParentSolution != null && ParentFolder == null) + return ParentSolution.ExtendedProperties; + else + return base.OnGetExtendedProperties (); } - + public override void Dispose() { if (items != null) { - foreach (SolutionItem e in items) + foreach (SolutionFolderItem e in items) e.Dispose (); items = null; } @@ -210,30 +207,25 @@ namespace MonoDevelop.Projects base.Dispose (); } - public SolutionItem ReloadItem (IProgressMonitor monitor, SolutionItem sitem) + public async Task<SolutionFolderItem> ReloadItem (ProgressMonitor monitor, SolutionFolderItem sitem) { if (Items.IndexOf (sitem) == -1) throw new InvalidOperationException ("Solution item '" + sitem.Name + "' does not belong to folder '" + Name + "'"); - SolutionEntityItem item = sitem as SolutionEntityItem; + SolutionItem item = sitem as SolutionItem; if (item != null) { // Load the new item - SolutionEntityItem newItem; + SolutionItem newItem; try { if (ParentSolution.IsSolutionItemEnabled (item.FileName)) - newItem = Services.ProjectService.ReadSolutionItem (monitor, item.FileName); + newItem = await Services.ProjectService.ReadSolutionItem (monitor, item.FileName); else { UnknownSolutionItem e = new UnloadedSolutionItem () { FileName = item.FileName }; - var ch = item.GetItemHandler () as MonoDevelop.Projects.Formats.MSBuild.MSBuildHandler; - if (ch != null) { - var h = new MonoDevelop.Projects.Formats.MSBuild.MSBuildHandler (ch.TypeGuid, ch.ItemId) { - Item = e, - }; - e.SetItemHandler (h); - } + e.ItemId = item.ItemId; + e.TypeGuid = item.TypeGuid; newItem = e; } } catch (Exception ex) { @@ -249,7 +241,7 @@ namespace MonoDevelop.Projects newItem.Dispose (); // Find the replacement if it exists - return Items.OfType<SolutionEntityItem> ().FirstOrDefault (it => it.FileName == item.FileName); + return Items.OfType<SolutionItem> ().FirstOrDefault (it => it.FileName == item.FileName); } // Replace in the file list @@ -269,7 +261,7 @@ namespace MonoDevelop.Projects return sitem; } - internal void NotifyItemAdded (SolutionItem item, bool newToSolution) + internal void NotifyItemAdded (SolutionFolderItem item, bool newToSolution) { ConnectChildEntryEvents (item); @@ -277,7 +269,7 @@ namespace MonoDevelop.Projects OnItemAdded (new SolutionItemChangeEventArgs (item, ParentSolution, false), newToSolution); } - void ConnectChildEntryEvents (SolutionItem item) + void ConnectChildEntryEvents (SolutionFolderItem item) { if (item is Project) { Project project = item as Project; @@ -303,42 +295,36 @@ namespace MonoDevelop.Projects folder.ReferenceAddedToProject += NotifyReferenceAddedToProject; } - if (item is SolutionEntityItem) { - ((SolutionEntityItem)item).Saved += NotifyItemSaved; + if (item is SolutionItem) { + ((SolutionItem)item).Saved += NotifyItemSaved; // ((SolutionEntityItem)item).ReloadRequired += NotifyItemReloadRequired; } item.Modified += NotifyItemModified; } - public override void Save (IProgressMonitor monitor) - { - foreach (SolutionItem item in Items) - item.Save (monitor); - } - - public SolutionEntityItem AddItem (IProgressMonitor monitor, string filename) + public Task<SolutionItem> AddItem (ProgressMonitor monitor, string filename) { return AddItem (monitor, filename, false); } - public SolutionEntityItem AddItem (IProgressMonitor monitor, string filename, bool createSolutionConfigurations) + public async Task<SolutionItem> AddItem (ProgressMonitor monitor, string filename, bool createSolutionConfigurations) { - if (monitor == null) monitor = new NullProgressMonitor (); - SolutionEntityItem entry = Services.ProjectService.ReadSolutionItem (monitor, filename); + if (monitor == null) monitor = new ProgressMonitor (); + SolutionItem entry = await Services.ProjectService.ReadSolutionItem (monitor, filename); AddItem (entry, createSolutionConfigurations); return entry; } - public void AddItem (SolutionItem item) + public void AddItem (SolutionFolderItem item) { AddItem (item, false); } - public void AddItem (SolutionItem item, bool createSolutionConfigurations) + public void AddItem (SolutionFolderItem item, bool createSolutionConfigurations) { Items.Add (item); - SolutionEntityItem eitem = item as SolutionEntityItem; + SolutionItem eitem = item as SolutionItem; if (eitem != null && createSolutionConfigurations && eitem.SupportsBuild ()) { // Create new solution configurations for item configurations foreach (ItemConfiguration iconf in eitem.Configurations) { @@ -352,7 +338,7 @@ namespace MonoDevelop.Projects if (!found) { SolutionConfiguration sconf = new SolutionConfiguration (iconf.Id); // Add all items to the new configuration - foreach (var it in ParentSolution.GetAllSolutionItems<SolutionEntityItem> ()) + foreach (var it in ParentSolution.GetAllItems<SolutionItem> ()) sconf.AddItem (it); ParentSolution.Configurations.Add (sconf); } @@ -360,14 +346,14 @@ namespace MonoDevelop.Projects } } - internal void NotifyItemRemoved (SolutionItem item, bool removedFromSolution) + internal void NotifyItemRemoved (SolutionFolderItem item, bool removedFromSolution) { DisconnectChildEntryEvents (item); NotifyModified ("Items"); OnItemRemoved (new SolutionItemChangeEventArgs (item, ParentSolution, false), removedFromSolution); } - void DisconnectChildEntryEvents (SolutionItem entry) + void DisconnectChildEntryEvents (SolutionFolderItem entry) { if (entry is Project) { Project pce = entry as Project; @@ -393,35 +379,29 @@ namespace MonoDevelop.Projects cce.ReferenceAddedToProject -= NotifyReferenceAddedToProject; } - if (entry is SolutionEntityItem) { - ((SolutionEntityItem)entry).Saved -= NotifyItemSaved; + if (entry is SolutionItem) { + ((SolutionItem)entry).Saved -= NotifyItemSaved; // ((SolutionEntityItem)entry).ReloadRequired -= NotifyItemReloadRequired; } entry.Modified -= NotifyItemModified; } - protected internal override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + public void Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { } - - /// <remarks> - /// Returns a collection containing all entries in this folder and - /// undercombines - /// </remarks> - public ReadOnlyCollection<SolutionItem> GetAllItems () + + public bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) { - return GetAllItems<SolutionItem> (); + return false; } - + /// <remarks> - /// Returns a collection containing all entries of the given type in this folder and + /// Returns a collection containing all entries in this folder and /// undercombines /// </remarks> - public ReadOnlyCollection<T> GetAllItems<T> () where T: SolutionItem + public IEnumerable<SolutionFolderItem> GetAllItems () { - List<T> list = new List<T> (); - GetAllItems<T> (list, this); - return list.AsReadOnly (); + return GetAllItems<SolutionFolderItem> (); } public ReadOnlyCollection<T> GetAllItemsWithTopologicalSort<T> (ConfigurationSelector configuration) where T: SolutionItem @@ -447,24 +427,24 @@ namespace MonoDevelop.Projects return SolutionItem.TopologicalSort<Project> (list, configuration); } - void GetAllItems<T> (List<T> list, SolutionItem item) where T: SolutionItem + void GetAllItems<T> (List<T> list, SolutionFolderItem item) where T: SolutionFolderItem { if (item is T) { list.Add ((T)item); } if (item is SolutionFolder) { - foreach (SolutionItem ce in ((SolutionFolder)item).Items) + foreach (SolutionFolderItem ce in ((SolutionFolder)item).Items) GetAllItems<T> (list, ce); } } public ReadOnlyCollection<SolutionItem> GetAllBuildableEntries (ConfigurationSelector configuration, bool topologicalSort, bool includeExternalReferences) { - List<SolutionItem> list = new List<SolutionItem> (); + var list = new List<SolutionItem> (); GetAllBuildableEntries (list, configuration, includeExternalReferences); if (topologicalSort) - return TopologicalSort<SolutionItem> (list, configuration); + return SolutionItem.TopologicalSort<SolutionItem> (list, configuration); else return list.AsReadOnly (); } @@ -482,22 +462,25 @@ namespace MonoDevelop.Projects if (conf == null) return; - foreach (SolutionItem item in Items) { + foreach (SolutionFolderItem item in Items) { if (item is SolutionFolder) ((SolutionFolder)item).GetAllBuildableEntries (list, configuration, includeExternalReferences); - else if ((item is SolutionEntityItem) && conf.BuildEnabledForItem ((SolutionEntityItem) item) && item.SupportsBuild ()) - GetAllBuildableReferences (list, item, configuration, includeExternalReferences); + else if ((item is SolutionItem) && conf.BuildEnabledForItem ((SolutionItem) item) && ((SolutionItem)item).SupportsBuild ()) + GetAllBuildableReferences (list, (SolutionItem)item, configuration, includeExternalReferences, false); } } - void GetAllBuildableReferences (List<SolutionItem> list, SolutionItem item, ConfigurationSelector configuration, bool includeExternalReferences) + void GetAllBuildableReferences (List<SolutionItem> list, SolutionItem item, ConfigurationSelector configuration, bool includeExternalReferences, bool isDirectReference) { if (list.Contains (item)) return; + // Skip unsupported projects which are not directly referenced by other (supported) projects + if (!isDirectReference && item.IsUnsupportedProject) + return; list.Add (item); if (includeExternalReferences) { - foreach (SolutionItem it in item.GetReferencedItems (configuration)) - GetAllBuildableReferences (list, it, configuration, includeExternalReferences); + foreach (var it in item.GetReferencedItems (configuration)) + GetAllBuildableReferences (list, it, configuration, includeExternalReferences, true); } } @@ -538,19 +521,19 @@ namespace MonoDevelop.Projects } } - public SolutionEntityItem FindSolutionItem (string fileName) + public SolutionItem FindSolutionItem (string fileName) { string path = Path.GetFullPath (fileName); - foreach (SolutionItem it in Items) { + foreach (SolutionFolderItem it in Items) { if (it is SolutionFolder) { - SolutionEntityItem r = ((SolutionFolder)it).FindSolutionItem (fileName); + SolutionItem r = ((SolutionFolder)it).FindSolutionItem (fileName); if (r != null) return r; } - else if (it is SolutionEntityItem) { - SolutionEntityItem se = (SolutionEntityItem) it; + else if (it is SolutionItem) { + SolutionItem se = (SolutionItem) it; if (!string.IsNullOrEmpty (se.FileName) && path == Path.GetFullPath (se.FileName)) - return (SolutionEntityItem) it; + return (SolutionItem) it; } } return null; @@ -558,7 +541,7 @@ namespace MonoDevelop.Projects public Project FindProjectByName (string name) { - foreach (SolutionItem it in Items) { + foreach (SolutionFolderItem it in Items) { if (it is SolutionFolder) { Project r = ((SolutionFolder)it).FindProjectByName (name); if (r != null) @@ -572,85 +555,42 @@ namespace MonoDevelop.Projects return null; } - protected internal override BuildResult OnRunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) + public async Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration) { - if (target == ProjectService.BuildTarget) - return OnBuild (monitor, configuration); - else if (target == ProjectService.CleanTarget) { - OnClean (monitor, configuration); + if (ParentSolution == null) return new BuildResult (); - } - + SolutionConfiguration conf = ParentSolution.GetConfiguration (configuration); + if (conf == null) + return new BuildResult (); + + var res = new BuildResult { BuildCount = 0 }; + ReadOnlyCollection<SolutionItem> allProjects; - try { allProjects = GetAllBuildableEntries (configuration, true, true); } catch (CyclicDependencyException) { monitor.ReportError (GettextCatalog.GetString ("Cyclic dependencies are not supported."), null); return new BuildResult ("", 1, 1); } - - try { - monitor.BeginTask (GettextCatalog.GetString ("Building Solution: {0} ({1})", Name, configuration.ToString ()), allProjects.Count); - - BuildResult cres = new BuildResult (); - cres.BuildCount = 0; - HashSet<SolutionItem> failedItems = new HashSet<SolutionItem> (); - - foreach (SolutionItem item in allProjects) { - if (monitor.IsCancelRequested) - break; - if (!item.ContainsReferences (failedItems, configuration)) { - BuildResult res = item.RunTarget (monitor, target, configuration); - if (res != null) { - cres.Append (res); - if (res.ErrorCount > 0) - failedItems.Add (item); - } - } else - failedItems.Add (item); - monitor.Step (1); - } - return cres; - } finally { - monitor.EndTask (); - } - } - - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) - { - if (ParentSolution == null) - return; - SolutionConfiguration conf = ParentSolution.GetConfiguration (configuration); - if (conf == null) - return; - + monitor.BeginTask (GettextCatalog.GetString ("Cleaning Solution: {0} ({1})", Name, configuration.ToString ()), allProjects.Count); try { - monitor.BeginTask (GettextCatalog.GetString ("Cleaning Solution: {0} ({1})", Name, configuration.ToString ()), Items.Count); - - foreach (SolutionItem item in Items) { - if (item is SolutionFolder) - item.Clean (monitor, configuration); - else if (item is SolutionEntityItem) { - SolutionEntityItem si = (SolutionEntityItem) item; - // ce can be null if you add items to the root solution folder which - // causes them to be placed in an autogenerated 'Project Items' folder - SolutionConfigurationEntry ce = conf.GetEntryForItem (si); - if (ce != null && ce.Build) - si.Clean (monitor, ce.ItemConfigurationSelector); - } else { - item.Clean (monitor, configuration); - } + foreach (var si in allProjects) { + // ce can be null if you add items to the root solution folder which + // causes them to be placed in an autogenerated 'Project Items' folder + SolutionConfigurationEntry ce = conf.GetEntryForItem (si); + if (ce != null && ce.Build) + res.Append (await si.Clean (monitor, ce.ItemConfigurationSelector)); monitor.Step (1); } } finally { monitor.EndTask (); } + return res; } - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + public async Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector configuration, bool buildReferencedTargets = false) { ReadOnlyCollection<SolutionItem> allProjects; @@ -671,11 +611,11 @@ namespace MonoDevelop.Projects HashSet<SolutionItem> failedItems = new HashSet<SolutionItem> (); foreach (SolutionItem item in toBuild) { - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) break; if (!item.ContainsReferences (failedItems, configuration)) { - BuildResult res = item.Build (monitor, configuration, false); + BuildResult res = await item.Build (monitor, configuration, false); if (res != null) { cres.Append (res); if (res.ErrorCount > 0) @@ -691,12 +631,17 @@ namespace MonoDevelop.Projects } } + public bool NeedsBuilding (ConfigurationSelector configuration) + { + return Items.OfType<IBuildTarget>().Any (t => t.NeedsBuilding (configuration)); + } + protected internal override DateTime OnGetLastBuildTime (ConfigurationSelector configuration) { // Return the min value, since that the last time all items in the // folder were built DateTime tim = DateTime.MaxValue; - foreach (SolutionItem it in Items) { + foreach (SolutionFolderItem it in Items) { DateTime t = it.GetLastBuildTime (configuration); if (t < tim) tim = t; @@ -1020,12 +965,12 @@ namespace MonoDevelop.Projects get { return folder.Name; } } - public BuildResult RunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) + public Task<BuildResult> RunTarget (ProgressMonitor monitor, string target, ConfigurationSelector configuration) { throw new NotImplementedException (); } - public void Save (IProgressMonitor monitor) + public Task Save (ProgressMonitor monitor) { throw new NotImplementedException (); } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolderItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolderItem.cs new file mode 100644 index 0000000000..9dd7b25a7d --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolderItem.cs @@ -0,0 +1,549 @@ +// SolutionItem.cs +// +// Author: +// Lluis Sanchez Gual <lluis@novell.com> +// +// Copyright (c) 2008 Novell, Inc (http://www.novell.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; +using System.Xml; +using MonoDevelop.Core; +using MonoDevelop.Core.Serialization; +using MonoDevelop.Projects.Extensions;
+using MonoDevelop.Core.StringParsing; +using MonoDevelop.Projects.Policies; +using System.Collections.Generic; +using MonoDevelop.Projects.Formats.MSBuild; + +namespace MonoDevelop.Projects +{ + public abstract class SolutionFolderItem: WorkspaceObject, IExtendedDataItem, IPolicyProvider + { + SolutionFolder parentFolder; + Solution parentSolution; + SolutionFolder internalChildren; + + [ProjectPathItemProperty ("BaseDirectory", DefaultValue=null)] + string baseDirectory; + + [ItemProperty ("Policies", IsExternal = true, SkipEmpty = true)] + PolicyBag policies; + + [ItemProperty ("UseMSBuildEngine")] + public bool? UseMSBuildEngine { get; set; } + + PropertyBag userProperties; + + internal List<string> UnresolvedProjectDependencies { get; set; } + + [ItemProperty ("name")] + public new string Name { + get { + return base.Name; + } + set { + if (value != Name) { + var oldName = Name; + OnSetName (value); + OnNameChanged (new SolutionItemRenamedEventArgs (this, oldName, Name)); + } + } + } + + public string TypeGuid { + get; + set; + } + + protected abstract void OnSetName (string value); + + /// <summary> + /// Gets the solution to which this item belongs + /// </summary> + public Solution ParentSolution { + get { + if (parentFolder != null) + return parentFolder.ParentSolution; + return parentSolution; + } + internal set { + if (parentSolution != null && parentSolution != value) + NotifyUnboundFromSolution (true); + parentSolution = value; + NotifyBoundToSolution (true); + } + } + + /// <summary> + /// Gets or sets the base directory of this solution item + /// </summary> + /// <value> + /// The base directory. + /// </value> + /// <remarks> + /// The base directory is the directory where files belonging to this project + /// are placed. Notice that this directory may be different than the directory + /// where the project file is placed. + /// </remarks> + public new FilePath BaseDirectory { + get { + if (baseDirectory == null) {
+ FilePath dir = GetDefaultBaseDirectory (); + if (dir.IsNullOrEmpty) + dir = "."; + return dir.FullPath; + } + else + return baseDirectory; + } + set {
+ FilePath def = GetDefaultBaseDirectory (); + if (value != FilePath.Null && def != FilePath.Null && value.FullPath == def.FullPath) + baseDirectory = null; + else if (string.IsNullOrEmpty (value)) + baseDirectory = null; + else + baseDirectory = value.FullPath; + NotifyModified ("BaseDirectory"); + } + } + + protected override string OnGetBaseDirectory () + { + return BaseDirectory; + } + + protected override string OnGetItemDirectory () + { + FilePath dir = GetDefaultBaseDirectory (); + if (string.IsNullOrEmpty (dir)) + dir = "."; + return dir.FullPath; + } + + internal bool HasCustomBaseDirectory { + get { return baseDirectory != null; } + }
+ + /// <summary> + /// Gets the default base directory. + /// </summary> + /// <remarks> + /// The base directory is the directory where files belonging to this project + /// are placed. Notice that this directory may be different than the directory + /// where the project file is placed. + /// </remarks> + protected virtual FilePath GetDefaultBaseDirectory ( ) + { + return ParentSolution.BaseDirectory; + } + + /// <summary> + /// Gets the identifier of this solution item + /// </summary> + /// <remarks> + /// The identifier is unique inside the solution + /// </remarks> + public string ItemId { + get { + if (itemId == null) + itemId = "{" + Guid.NewGuid ().ToString ().ToUpper () + "}"; + return itemId; + } + set { + itemId = value; + } + } + + string itemId; + + /// <summary> + /// Gets policies. + /// </summary> + /// <remarks> + /// Returns a policy container which can be used to query policies specific for this + /// solution item. If a policy is not defined for this item, the inherited value will be returned. + /// </remarks> + public PolicyBag Policies { + get { + //newly created (i.e. not deserialised) SolutionItems may have a null PolicyBag + if (policies == null) + policies = new MonoDevelop.Projects.Policies.PolicyBag (); + //this is the easiest reliable place to associate a deserialised Policybag with its owner + policies.Owner = this; + return policies; + } + //setter so that a solution can deserialise the PropertyBag on its RootFolder + internal set { + policies = value; + } + } + + PolicyContainer IPolicyProvider.Policies { + get { + return Policies; + } + } + + /// <summary> + /// Gets solution item properties specific to the current user + /// </summary> + /// <remarks> + /// These properties are not stored in the project file, but in a separate file which is not to be shared + /// with other users. + /// User properties are only loaded when the project is loaded inside the IDE. + /// </remarks> + public PropertyBag UserProperties { + get { + if (userProperties == null) + userProperties = new PropertyBag (); + return userProperties; + } + } + + /// <summary> + /// Initializes the user properties of the item + /// </summary> + /// <param name='properties'> + /// Properties to be set + /// </param> + /// <exception cref='InvalidOperationException'> + /// The user properties have already been set + /// </exception> + /// <remarks> + /// This method is used by the IDE to initialize the user properties when a project is loaded. + /// </remarks> + public void LoadUserProperties (PropertyBag properties) + { + if (userProperties != null) + throw new InvalidOperationException ("User properties already loaded."); + userProperties = properties; + } + + /// <summary> + /// Gets the parent solution folder. + /// </summary> + public SolutionFolder ParentFolder { + get { + return parentFolder; + } + internal set { + if (parentFolder != null && parentFolder.ParentSolution != null && (value == null || value.ParentSolution != parentFolder.ParentSolution)) + NotifyUnboundFromSolution (false); + + parentFolder = value; + if (internalChildren != null) { + internalChildren.ParentFolder = value; + } + if (value != null && value.ParentSolution != null) { + NotifyBoundToSolution (false); + } + } + } + + // Normally, the ParentFolder setter fires OnBoundToSolution. However, when deserializing, child + // ParentFolder hierarchies can become connected before the ParentSolution becomes set. This method + // enables us to recursively fire the OnBoundToSolution call in those cases. + void NotifyBoundToSolution (bool includeInternalChildren) + { + var folder = this as SolutionFolder; + if (folder != null) { + var items = folder.GetItemsWithoutCreating (); + if (items != null) { + foreach (var item in items) { + item.NotifyBoundToSolution (true); + } + } + } + if (includeInternalChildren && internalChildren != null) { + internalChildren.NotifyBoundToSolution (true); + } + OnBoundToSolution (); + } + + void NotifyUnboundFromSolution (bool includeInternalChildren) + { + var folder = this as SolutionFolder; + if (folder != null) { + var items = folder.GetItemsWithoutCreating (); + if (items != null) { + foreach (var item in items) { + item.NotifyUnboundFromSolution (true); + } + } + } + if (includeInternalChildren && internalChildren != null) { + internalChildren.NotifyUnboundFromSolution (true); + } + OnUnboundFromSolution (); + } + + /// <summary> + /// Releases all resource used by the <see cref="MonoDevelop.Projects.SolutionItem"/> object. + /// </summary> + /// <remarks> + /// Call <see cref="Dispose"/> when you are finished using the <see cref="MonoDevelop.Projects.SolutionItem"/>. The + /// <see cref="Dispose"/> method leaves the <see cref="MonoDevelop.Projects.SolutionItem"/> in an unusable state. + /// After calling <see cref="Dispose"/>, you must release all references to the + /// <see cref="MonoDevelop.Projects.SolutionItem"/> so the garbage collector can reclaim the memory that the + /// <see cref="MonoDevelop.Projects.SolutionItem"/> was occupying. + /// </remarks> + public override void Dispose () + { + base.Dispose (); + + if (userProperties != null) { + ((IDisposable)userProperties).Dispose (); + userProperties = null; + } + + // parentFolder = null; + // parentSolution = null; + // internalChildren = null; + // policies = null; + } + + /// <summary> + /// Gets the time of the last build + /// </summary> + /// <returns> + /// The last build time. + /// </returns> + /// <param name='configuration'> + /// Configuration for which to get the last build time. + /// </param> + public DateTime GetLastBuildTime (ConfigurationSelector configuration) + { + return OnGetLastBuildTime (configuration); + } + + /// <summary> + /// Gets or sets a value indicating whether this <see cref="MonoDevelop.Projects.SolutionItem"/> needs to be reload due to changes in project or solution file + /// </summary> + /// <value> + /// <c>true</c> if needs reload; otherwise, <c>false</c>. + /// </value> + public virtual bool NeedsReload { + get { + if (ParentSolution != null) + return ParentSolution.NeedsReload; + else + return false; + } + set { + } + } + + /// <summary> + /// Registers an internal child item. + /// </summary> + /// <param name='item'> + /// An item + /// </param> + /// <remarks> + /// Some kind of projects may be composed of several child projects. + /// By registering those child projects using this method, the child + /// projects will be plugged into the parent solution infrastructure + /// (so for example, the ParentSolution property for those projects + /// will return the correct value) + /// </remarks> + protected void RegisterInternalChild (SolutionFolderItem item) + { + if (internalChildren == null) { + internalChildren = new SolutionFolder (); + internalChildren.ParentFolder = parentFolder; + } + internalChildren.Items.Add (item); + } + + /// <summary> + /// Unregisters an internal child item. + /// </summary> + /// <param name='item'> + /// The item + /// </param> + protected void UnregisterInternalChild (SolutionFolderItem item) + { + if (internalChildren != null) + internalChildren.Items.Remove (item); + } + + /// <summary> + /// Gets the string tag model description for this solution item + /// </summary> + /// <returns> + /// The string tag model description + /// </returns> + /// <param name='conf'> + /// Configuration for which to get the string tag model description + /// </param> + public virtual StringTagModelDescription GetStringTagModelDescription (ConfigurationSelector conf) + { + StringTagModelDescription model = new StringTagModelDescription (); + model.Add (GetType ()); + model.Add (typeof(Solution)); + return model; + } + + /// <summary> + /// Gets the string tag model for this solution item + /// </summary> + /// <returns> + /// The string tag model + /// </returns> + /// <param name='conf'> + /// Configuration for which to get the string tag model + /// </param> + public virtual StringTagModel GetStringTagModel (ConfigurationSelector conf) + { + StringTagModel source = new StringTagModel (); + source.Add (this); + if (ParentSolution != null) + source.Add (ParentSolution.GetStringTagModel ()); + return source; + } + + /// <summary> + /// Gets the author information for this solution item, inherited from the solution and global settings. + /// </summary> + public AuthorInformation AuthorInformation { + get { + if (ParentSolution != null) + return ParentSolution.AuthorInformation; + else + return AuthorInformation.Default; + } + } + + internal MSBuildFileFormat SolutionFormat { get; private set; } + + internal virtual void SetSolutionFormat (MSBuildFileFormat format, bool converting) + { + this.SolutionFormat = format; + } + + public virtual bool HasSlnData { + get { return false; } + } + + DataItem customSlnData; + + public virtual DataItem WriteSlnData () + { + return customSlnData; + } + + public virtual void ReadSlnData (DataItem item) + { + customSlnData = item; + } + + /// <summary> + /// Notifies that this solution item has been modified + /// </summary> + /// <param name='hint'> + /// Hint about which part of the solution item has been modified. This will typically be the property name. + /// </param> + public void NotifyModified (string hint) + { + OnModified (new SolutionItemModifiedEventArgs (this, hint)); + } + + /// <summary> + /// Raises the modified event. + /// </summary> + /// <param name='args'> + /// Arguments. + /// </param> + protected virtual void OnModified (SolutionItemModifiedEventArgs args) + { + if (Modified != null && !Disposed) + Modified (this, args); + } + + /// <summary> + /// Raises the name changed event. + /// </summary> + /// <param name='e'> + /// Arguments. + /// </param> + protected virtual void OnNameChanged (SolutionItemRenamedEventArgs e) + { + NotifyModified ("Name"); + if (NameChanged != null && !Disposed) + NameChanged (this, e); + } + + /// <summary> + /// Initializes the item handler. + /// </summary> + /// <remarks> + /// This method is called the first time an item handler is requested. + /// Subclasses should override this method use SetItemHandler to + /// assign a handler to this item. + /// </remarks> + protected virtual void InitializeItemHandler () + { + } + + /// <summary> + /// Gets the time of the last build + /// </summary> + /// <returns> + /// The last build time. + /// </returns> + /// <param name='configuration'> + /// Configuration for which to get the last build time. + /// </param> + internal protected virtual DateTime OnGetLastBuildTime (ConfigurationSelector configuration) + { + return DateTime.MinValue; + } + + /// <summary> + /// Called just after this item is bound to a solution + /// </summary> + protected virtual void OnBoundToSolution () + { + } + + /// <summary> + /// Called just before this item is removed from a solution (ParentSolution is still valid when this method is called) + /// </summary> + protected virtual void OnUnboundFromSolution () + { + } + + /// <summary> + /// Occurs when the name of the item changes + /// </summary> + public event SolutionItemRenamedEventHandler NameChanged; + + /// <summary> + /// Occurs when the item is modified. + /// </summary> + public event SolutionItemModifiedEventHandler Modified; + } + +} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolderItemCollection.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolderItemCollection.cs index e6704c7a57..81b85305e1 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolderItemCollection.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionFolderItemCollection.cs @@ -30,7 +30,7 @@ using System.Collections.ObjectModel; namespace MonoDevelop.Projects { - public class SolutionFolderItemCollection: ItemCollection<SolutionItem> + public class SolutionFolderItemCollection: ItemCollection<SolutionFolderItem> { SolutionFolder parentFolder; @@ -43,14 +43,14 @@ namespace MonoDevelop.Projects this.parentFolder = parentFolder; } - internal void Replace (SolutionItem item, SolutionItem newItem) + internal void Replace (SolutionFolderItem item, SolutionFolderItem newItem) { int i = IndexOf (item); Items [i] = newItem; newItem.ParentFolder = parentFolder; } - protected override void OnItemAdded (SolutionItem item) + protected override void OnItemAdded (SolutionFolderItem item) { if (parentFolder != null) { // If the item belongs to another solution, remove it from there. @@ -74,7 +74,7 @@ namespace MonoDevelop.Projects } } - protected override void OnItemRemoved (SolutionItem item) + protected override void OnItemRemoved (SolutionFolderItem item) { if (parentFolder != null) { item.ParentFolder = null; @@ -82,12 +82,12 @@ namespace MonoDevelop.Projects } } - internal void InternalAdd (SolutionItem item) + internal void InternalAdd (SolutionFolderItem item) { Items.Add (item); } - internal void InternalRemove (SolutionItem item) + internal void InternalRemove (SolutionFolderItem item) { Items.Remove (item); } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItem.cs index 3dd753efab..4cf410e674 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItem.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItem.cs @@ -1,4 +1,4 @@ -// SolutionItem.cs +// SolutionEntityItem.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> @@ -26,419 +26,301 @@ // using System; +using System.Linq; +using System.Xml; +using System.IO; using System.Collections; -using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Xml; +using System.Collections.Specialized; +using System.Collections.Generic; +using System.Reflection; +using System.Diagnostics; using System.CodeDom.Compiler; + using MonoDevelop.Core; +using MonoDevelop.Projects; using MonoDevelop.Core.Serialization; -using MonoDevelop.Projects.Extensions;
-using MonoDevelop.Core.Collections; +using MonoDevelop.Projects.Extensions; using MonoDevelop.Core.StringParsing; -using MonoDevelop.Core.Instrumentation; -using MonoDevelop.Projects.Policies; using MonoDevelop.Core.Execution; +using Mono.Addins; +using MonoDevelop.Core.Instrumentation; +using MonoDevelop.Core.Collections; +using System.Threading.Tasks; +using MonoDevelop.Projects.Formats.MSBuild; namespace MonoDevelop.Projects { - public abstract class SolutionItem: IExtendedDataItem, IBuildTarget, ILoadController, IPolicyProvider + public abstract class SolutionItem : SolutionFolderItem, IWorkspaceFileObject, IConfigurationTarget, ILoadController, IBuildTarget { - SolutionFolder parentFolder; - Solution parentSolution; - ISolutionItemHandler handler; + internal object MemoryProbe = Counters.ItemsInMemory.CreateMemoryProbe (); + int loading; - SolutionFolder internalChildren; + ProjectItemCollection items; + ProjectItemCollection wildcardItems; + ItemCollection<SolutionItem> dependencies = new ItemCollection<SolutionItem> (); + + SolutionItemEventArgs thisItemArgs; - [ProjectPathItemProperty ("BaseDirectory", DefaultValue=null)] - string baseDirectory; + FileStatusTracker<SolutionItemEventArgs> fileStatusTracker; + + FilePath fileName; + string name; - Hashtable extendedProperties; + FileFormat fileFormat; - [ItemProperty ("Policies", IsExternal = true, SkipEmpty = true)] - MonoDevelop.Projects.Policies.PolicyBag policies; + SolutionItemConfiguration activeConfiguration; + SolutionItemConfigurationCollection configurations; - [ItemProperty ("UseMSBuildEngine")] - public bool? UseMSBuildEngine { get; set; } - - PropertyBag userProperties; + public event EventHandler ConfigurationsChanged; + public event ConfigurationEventHandler DefaultConfigurationChanged; + public event ConfigurationEventHandler ConfigurationAdded; + public event ConfigurationEventHandler ConfigurationRemoved; + public event EventHandler<ProjectItemEventArgs> ProjectItemAdded; + public event EventHandler<ProjectItemEventArgs> ProjectItemRemoved; + + // When set, it means this item is saved as part of a global solution save operation + internal bool SavingSolution { get; set; } - /// <summary> - /// Initializes a new instance of the <see cref="MonoDevelop.Projects.SolutionItem"/> class. - /// </summary> - public SolutionItem() + public SolutionItem () { + var fmt = Services.ProjectService.FileFormats.GetFileFormat (MSBuildProjectService.DefaultFormat); + TypeGuid = MSBuildProjectService.GetTypeGuidForItem (this); + + SetSolutionFormat ((MSBuildFileFormat)fmt.Format, true); ProjectExtensionUtil.LoadControl (this); + items = new ProjectItemCollection (this); + wildcardItems = new ProjectItemCollection (this); + thisItemArgs = new SolutionItemEventArgs (this); + configurations = new SolutionItemConfigurationCollection (this); + configurations.ConfigurationAdded += OnConfigurationAddedToCollection; + configurations.ConfigurationRemoved += OnConfigurationRemovedFromCollection; + Counters.ItemsLoaded++; + fileStatusTracker = new FileStatusTracker<SolutionItemEventArgs> (this, OnReloadRequired, new SolutionItemEventArgs (this)); } - - /// <summary> - /// Initializes a new instance of this item, using an xml element as template - /// </summary> - /// <param name='template'> - /// The template - /// </param> - public virtual void InitializeFromTemplate (XmlElement template) - { - } - - /// <summary> - /// Gets the handler for this solution item - /// </summary> - /// <value> - /// The solution item handler. - /// </value> - /// <exception cref='InvalidOperationException'> - /// Is thrown if there isn't a ISolutionItemHandler for this solution item - /// </exception> - protected internal ISolutionItemHandler ItemHandler { + + SolutionItemExtension itemExtension; + + SolutionItemExtension ItemExtension { get { - if (handler == null) { - InitializeItemHandler (); - if (handler == null) - throw new InvalidOperationException ("No handler found for solution item of type: " + GetType ()); - } - return handler; + if (itemExtension == null) + itemExtension = ExtensionChain.GetExtension<SolutionItemExtension> (); + return itemExtension; } } - - /// <summary> - /// Sets the handler for this solution item - /// </summary> - /// <param name='handler'> - /// A handler. - /// </param> - internal virtual void SetItemHandler (ISolutionItemHandler handler) + + protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions () { - if (this.handler != null) - this.handler.Dispose (); - this.handler = handler; + foreach (var e in base.CreateDefaultExtensions ()) + yield return e; + yield return new DefaultMSBuildItemExtension (); } - - internal ISolutionItemHandler GetItemHandler () + + internal protected virtual IEnumerable<string> GetItemTypeGuids () { - // Used to get the handler without lazy loading it - return this.handler; + yield return TypeGuid; } - - /// <summary> - /// Gets the author information for this solution item, inherited from the solution and global settings. - /// </summary> - public AuthorInformation AuthorInformation { - get { - if (ParentSolution != null) - return ParentSolution.AuthorInformation; - else - return AuthorInformation.Default; - } - } - - /// <summary> - /// Gets a service instance of a given type - /// </summary> - /// <returns> - /// The service. - /// </returns> - /// <typeparam name='T'> - /// Type of the service - /// </typeparam> - /// <remarks> - /// This method looks for an imlpementation of a service of the given type. - /// </remarks> - public T GetService<T> () where T: class + + public override void Dispose () { - return (T) GetService (typeof(T)); + base.Dispose (); + Counters.ItemsLoaded--; + + foreach (var item in items.Concat (wildcardItems)) { + IDisposable disp = item as IDisposable; + if (disp != null) + disp.Dispose (); + } + + // items = null; + // wildcardItems = null; + // thisItemArgs = null; + // fileStatusTracker = null; + // fileFormat = null; + // activeConfiguration = null; + // configurations = null; } - /// <summary> - /// Gets a service instance of a given type - /// </summary> - /// <returns> - /// The service. - /// </returns> - /// <param name='t'> - /// Type of the service - /// </param> - /// <remarks> - /// This method looks for an imlpementation of a service of the given type. - /// </remarks> - public virtual object GetService (Type t) + void HandleSolutionItemAdded (object sender, SolutionItemChangeEventArgs e) { - return Services.ProjectService.GetExtensionChain (this).GetService (this, t); - } - - /// <summary> - /// Gets the solution to which this item belongs - /// </summary> - public Solution ParentSolution { - get { - if (parentFolder != null) - return parentFolder.ParentSolution; - return parentSolution; - } - internal set { - parentSolution = value; - NotifyBoundToSolution (true); + if (e.Reloading && dependencies.Count > 0 && (e.SolutionItem is SolutionItem) && (e.ReplacedItem is SolutionItem)) { + int i = dependencies.IndexOf ((SolutionItem)e.ReplacedItem); + if (i != -1) + dependencies [i] = (SolutionItem) e.SolutionItem; } } - /// <summary> - /// Gets a value indicating whether this item is currently being loaded from a file - /// </summary> - /// <remarks> - /// While an item is loading, some events such as project file change events may be fired. - /// This flag can be used to check if change events are caused by data being loaded. - /// </remarks> - public bool Loading { - get { return loading > 0; } - } - - /// <summary> - /// Saves the solution item - /// </summary> - /// <param name='monitor'> - /// A progress monitor. - /// </param> - public abstract void Save (IProgressMonitor monitor); - - /// <summary> - /// Name of the solution item - /// </summary> - public abstract string Name { get; set; } - - /// <summary> - /// Gets or sets the base directory of this solution item - /// </summary> - /// <value> - /// The base directory. - /// </value> - /// <remarks> - /// The base directory is the directory where files belonging to this project - /// are placed. Notice that this directory may be different than the directory - /// where the project file is placed. - /// </remarks> - public FilePath BaseDirectory { - get { - if (baseDirectory == null) {
- FilePath dir = GetDefaultBaseDirectory (); - if (dir.IsNullOrEmpty) - dir = "."; - return dir.FullPath; - } - else - return baseDirectory; - } - set {
- FilePath def = GetDefaultBaseDirectory (); - if (value != FilePath.Null && def != FilePath.Null && value.FullPath == def.FullPath) - baseDirectory = null; - else if (string.IsNullOrEmpty (value)) - baseDirectory = null; - else - baseDirectory = value.FullPath; - NotifyModified ("BaseDirectory"); - } + void HandleSolutionItemRemoved (object sender, SolutionItemChangeEventArgs e) + { + if (!e.Reloading && (e.SolutionItem is SolutionItem)) + dependencies.Remove ((SolutionItem)e.SolutionItem); } - - /// <summary> - /// Gets the directory where this solution item is placed - /// </summary> - public FilePath ItemDirectory { - get {
- FilePath dir = GetDefaultBaseDirectory (); - if (string.IsNullOrEmpty (dir)) - dir = "."; - return dir.FullPath; - } + + void ILoadController.BeginLoad () + { + loading++; + OnBeginLoad (); } - - internal bool HasCustomBaseDirectory { - get { return baseDirectory != null; } - }
- - /// <summary> - /// Gets the default base directory. - /// </summary> - /// <remarks> - /// The base directory is the directory where files belonging to this project - /// are placed. Notice that this directory may be different than the directory - /// where the project file is placed. - /// </remarks> - protected virtual FilePath GetDefaultBaseDirectory ( ) + + void ILoadController.EndLoad () { - return ParentSolution.BaseDirectory; + loading--; + OnEndLoad (); } /// <summary> - /// Gets the identifier of this solution item + /// Called when a load operation for this solution item has started /// </summary> - /// <remarks> - /// The identifier is unique inside the solution - /// </remarks> - public string ItemId { - get { return ItemHandler.ItemId; } + protected virtual void OnBeginLoad () + { } - + /// <summary> - /// Gets extended properties. + /// Called when a load operation for this solution item has finished /// </summary> - /// <remarks> - /// This dictionary can be used by add-ins to store arbitrary information about this solution item. - /// Keys and values can be of any type. - /// If a value implements IDisposable, the value will be disposed when this solution item is disposed. - /// Values in this dictionary won't be serialized, unless they are registered as serializable using - /// the /MonoDevelop/ProjectModel/ExtendedProperties extension point. - /// </remarks> - public IDictionary ExtendedProperties { - get { return InternalGetExtendedProperties; } + protected virtual void OnEndLoad () + { + fileStatusTracker.ResetLoadTimes (); + + if (syncReleaseVersion && ParentSolution != null) + releaseVersion = ParentSolution.Version; } + + [ItemProperty ("ReleaseVersion", DefaultValue="0.1")] + string releaseVersion = "0.1"; - /// <summary> - /// Gets policies. - /// </summary> - /// <remarks> - /// Returns a policy container which can be used to query policies specific for this - /// solution item. If a policy is not defined for this item, the inherited value will be returned. - /// </remarks> - public MonoDevelop.Projects.Policies.PolicyBag Policies { + [ItemProperty ("SynchReleaseVersion", DefaultValue = true)] + bool syncReleaseVersion = true; + + public string Version { get { - //newly created (i.e. not deserialised) SolutionItems may have a null PolicyBag - if (policies == null) - policies = new MonoDevelop.Projects.Policies.PolicyBag (); - //this is the easiest reliable place to associate a deserialised Policybag with its owner - policies.Owner = this; - return policies; + // If syncReleaseVersion is set, releaseVersion will already contain the solution's version + // That's because the version must be up to date even when loading the project individually + return releaseVersion; } - //setter so that a solution can deserialise the PropertyBag on its RootFolder - internal set { - policies = value; + set { + releaseVersion = value; + NotifyModified ("Version"); } } - PolicyContainer IPolicyProvider.Policies { + public bool SyncVersionWithSolution { get { - return Policies; + return syncReleaseVersion; + } + set { + syncReleaseVersion = value; + if (syncReleaseVersion && ParentSolution != null) + Version = ParentSolution.Version; + NotifyModified ("SyncVersionWithSolution"); } } - /// <summary> - /// Gets solution item properties specific to the current user - /// </summary> - /// <remarks> - /// These properties are not stored in the project file, but in a separate file which is not to be shared - /// with other users. - /// User properties are only loaded when the project is loaded inside the IDE. - /// </remarks> - public PropertyBag UserProperties { - get { - if (userProperties == null) - userProperties = new PropertyBag (); - return userProperties; + protected override string OnGetName () + { + return name ?? string.Empty; + } + + protected override void OnSetName (string value) + { + name = value; + if (!Loading && SyncFileName) { + if (string.IsNullOrEmpty (fileName)) + FileName = value; + else { + string ext = fileName.Extension; + FileName = fileName.ParentDirectory.Combine (value) + ext; + } } } - + /// <summary> - /// Initializes the user properties of the item + /// Returns a value indicating whether the name of the solution item should be the same as the name of the file /// </summary> - /// <param name='properties'> - /// Properties to be set - /// </param> - /// <exception cref='InvalidOperationException'> - /// The user properties have already been set - /// </exception> - /// <remarks> - /// This method is used by the IDE to initialize the user properties when a project is loaded. - /// </remarks> - public void LoadUserProperties (PropertyBag properties) - { - if (userProperties != null) - throw new InvalidOperationException ("User properties already loaded."); - userProperties = properties; + /// <value> + /// <c>true</c> if the file name must be in sync with the solution item name; otherwise, <c>false</c>. + /// </value> + protected virtual bool SyncFileName { + get { return true; } } - /// <summary> - /// Gets the parent solution folder. - /// </summary> - public SolutionFolder ParentFolder { + public virtual FilePath FileName { get { - return parentFolder; + return fileName; } - internal set { - parentFolder = value; - if (internalChildren != null) { - internalChildren.ParentFolder = value; - } - if (value != null && value.ParentSolution != null) { - NotifyBoundToSolution (false); + set { + if (FileFormat != null) + value = FileFormat.GetValidFileName (this, value); + if (value != fileName) { + fileName = value; + if (SyncFileName) + Name = fileName.FileNameWithoutExtension; + NotifyModified ("FileName"); } } } - // Normally, the ParentFolder setter fires OnBoundToSolution. However, when deserializing, child - // ParentFolder hierarchies can become connected before the ParentSolution becomes set. This method - // enables us to recursively fire the OnBoundToSolution call in those cases. - void NotifyBoundToSolution (bool includeInternalChildren) - { - var folder = this as SolutionFolder; - if (folder != null) { - var items = folder.GetItemsWithoutCreating (); - if (items != null) { - foreach (var item in items) { - item.NotifyBoundToSolution (includeInternalChildren); - } + public bool Enabled { + get { return ParentSolution != null ? ParentSolution.IsSolutionItemEnabled (FileName) : true; } + set { + if (ParentSolution != null) + ParentSolution.SetSolutionItemEnabled (FileName, value); + } + } + + public FileFormat FileFormat { + get { + if (ParentSolution != null) { + if (ParentSolution.FileFormat.Format.SupportsMixedFormats && fileFormat != null) + return fileFormat; + return ParentSolution.FileFormat; } + if (fileFormat == null) + fileFormat = Services.ProjectService.GetDefaultFormat (this); + return fileFormat; } - if (includeInternalChildren && internalChildren != null) { - internalChildren.NotifyBoundToSolution (includeInternalChildren); + set { + if (ParentSolution != null && !ParentSolution.FileFormat.Format.SupportsMixedFormats) + throw new InvalidOperationException ("The file format can't be changed when the item belongs to a solution."); + InstallFormat (value); + fileFormat.Format.ConvertToFormat (this); + NeedsReload = false; + NotifyModified ("FileFormat"); } - OnBoundToSolution (); + } + + protected override object OnGetService (Type t) + { + return null; } + public ProjectItemCollection Items { + get { return items; } + } + internal ProjectItemCollection WildcardItems { + get { return wildcardItems; } + } + /// <summary> - /// Gets a value indicating whether this <see cref="MonoDevelop.Projects.SolutionItem"/> has been disposed. + /// Projects that need to be built before building this one /// </summary> - /// <value> - /// <c>true</c> if disposed; otherwise, <c>false</c>. - /// </value> - internal protected bool Disposed { get; private set; } + /// <value>The dependencies.</value> + public ItemCollection<SolutionItem> ItemDependencies { + get { return dependencies; } + } /// <summary> - /// Releases all resource used by the <see cref="MonoDevelop.Projects.SolutionItem"/> object. + /// Gets a value indicating whether this item is currently being loaded from a file /// </summary> /// <remarks> - /// Call <see cref="Dispose"/> when you are finished using the <see cref="MonoDevelop.Projects.SolutionItem"/>. The - /// <see cref="Dispose"/> method leaves the <see cref="MonoDevelop.Projects.SolutionItem"/> in an unusable state. - /// After calling <see cref="Dispose"/>, you must release all references to the - /// <see cref="MonoDevelop.Projects.SolutionItem"/> so the garbage collector can reclaim the memory that the - /// <see cref="MonoDevelop.Projects.SolutionItem"/> was occupying. + /// While an item is loading, some events such as project file change events may be fired. + /// This flag can be used to check if change events are caused by data being loaded. /// </remarks> - public virtual void Dispose () - { - Disposed = true; - - if (extendedProperties != null) { - foreach (object ob in extendedProperties.Values) { - IDisposable disp = ob as IDisposable; - if (disp != null) - disp.Dispose (); - } - extendedProperties = null; - } - if (handler != null) { - handler.Dispose (); - // handler = null; - } - if (userProperties != null) { - ((IDisposable)userProperties).Dispose (); - userProperties = null; - } - - // parentFolder = null; - // parentSolution = null; - // internalChildren = null; - // policies = null; + public bool Loading { + get { return loading > 0; } } - + /// <summary> /// Gets solution items referenced by this instance (items on which this item depends) /// </summary> @@ -448,94 +330,215 @@ namespace MonoDevelop.Projects /// <param name='configuration'> /// Configuration for which to get the referenced items /// </param> - public virtual IEnumerable<SolutionItem> GetReferencedItems (ConfigurationSelector configuration) + public IEnumerable<SolutionItem> GetReferencedItems (ConfigurationSelector configuration) + { + return ItemExtension.OnGetReferencedItems (configuration); + } + + protected virtual IEnumerable<SolutionItem> OnGetReferencedItems (ConfigurationSelector configuration) + { + return dependencies; + } + + Task IWorkspaceFileObject.ConvertToFormat (FileFormat format, bool convertChildren) + { + this.FileFormat = format; + return Task.FromResult (0); + } + + public bool SupportsFormat (FileFormat format) + { + return ItemExtension.OnGetSupportsFormat (format); + } + + protected virtual bool OnGetSupportsFormat (FileFormat format) + { + return true; + } + + internal void InstallFormat (FileFormat format) { - return new SolutionItem [0]; + fileFormat = format; + if (fileName != FilePath.Null) + fileName = fileFormat.GetValidFileName (this, fileName); } /// <summary> - /// Runs a build or execution target. + /// Initializes a new instance of this item, using an xml element as template /// </summary> - /// <returns> - /// The result of the operation - /// </returns> - /// <param name='monitor'> - /// A progress monitor - /// </param> - /// <param name='target'> - /// Name of the target - /// </param> - /// <param name='configuration'> - /// Configuration to use to run the target + /// <param name='template'> + /// The template /// </param> - public BuildResult RunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) + public void InitializeFromTemplate (XmlElement template) { - return Services.ProjectService.GetExtensionChain (this).RunTarget (monitor, this, target, configuration); + ItemExtension.OnInitializeFromTemplate (template); } - - public bool SupportsTarget (string target) + + protected virtual void OnInitializeFromTemplate (XmlElement template) { - return Services.ProjectService.GetExtensionChain (this).SupportsTarget (this, target); } - public bool SupportsBuild () + public virtual void InitializeNew (ProjectCreateInformation projectCreateInfo, XmlElement projectOptions) { - return SupportsTarget (ProjectService.BuildTarget); } - public bool SupportsExecute () + protected override FilePath GetDefaultBaseDirectory ( ) { - return Services.ProjectService.GetExtensionChain (this).SupportsExecute (this); + return ItemExtension.OnGetDefaultBaseDirectory (); } + internal Task LoadAsync (ProgressMonitor monitor, FilePath fileName, MSBuildFileFormat format) + { + FileName = fileName; + Name = Path.GetFileNameWithoutExtension (fileName); + SetSolutionFormat (format ?? new MSBuildFileFormatVS12 (), false); + return ItemExtension.OnLoad (monitor); + } + + public void Save (ProgressMonitor monitor, FilePath fileName) + { + SaveAsync (monitor, fileName).Wait (); + } + + public Task SaveAsync (ProgressMonitor monitor, FilePath fileName) + { + FileName = fileName; + return SaveAsync (monitor); + } + /// <summary> - /// Cleans the files produced by this solution item + /// Saves the solution item /// </summary> /// <param name='monitor'> - /// A progress monitor - /// </param> - /// <param name='configuration'> - /// Configuration to use to clean the project + /// A progress monitor. /// </param> - public void Clean (IProgressMonitor monitor, ConfigurationSelector configuration) + public void Save (ProgressMonitor monitor) { - ITimeTracker tt = Counters.BuildProjectTimer.BeginTiming ("Cleaning " + Name); + ItemExtension.OnSave (monitor).Wait (); + } + + + public async Task SaveAsync (ProgressMonitor monitor) + { + await ItemExtension.OnSave (monitor); + + if (HasSlnData && !SavingSolution && ParentSolution != null) { + // The project has data that has to be saved in the solution, but the solution is not being saved. Do it now. + await SolutionFormat.SlnFileFormat.WriteFile (ParentSolution.FileName, ParentSolution, false, monitor); + ParentSolution.NeedsReload = false; + } + } + + async Task DoSave (ProgressMonitor monitor) + { + if (string.IsNullOrEmpty (FileName)) + throw new InvalidOperationException ("Project does not have a file name"); + try { - //SolutionFolder handles the begin/end task itself, don't duplicate - if (this is SolutionFolder) { - RunTarget (monitor, ProjectService.CleanTarget, configuration); - return; - } - - try { - SolutionEntityItem it = this as SolutionEntityItem; - SolutionItemConfiguration iconf = it != null ? it.GetConfiguration (configuration) : null; - string confName = iconf != null ? iconf.Id : configuration.ToString (); - monitor.BeginTask (GettextCatalog.GetString ("Cleaning: {0} ({1})", Name, confName), 1); - RunTarget (monitor, ProjectService.CleanTarget, configuration); - } finally { - monitor.EndTask (); - } + fileStatusTracker.BeginSave (); + await OnSave (monitor); + OnSaved (thisItemArgs); + } finally { + fileStatusTracker.EndSave (); } - finally { - tt.End (); + FileService.NotifyFileChanged (FileName); + } + + internal bool IsSaved { + get { + return !string.IsNullOrEmpty (FileName) && File.Exists (FileName); } } + public override bool NeedsReload { + get { return fileStatusTracker.NeedsReload; } + set { fileStatusTracker.NeedsReload = value; } + } + + public virtual bool ItemFilesChanged { + get { return ItemExtension.ItemFilesChanged; } + } + + bool BaseItemFilesChanged { + get { return fileStatusTracker.ItemFilesChanged; } + } + + public bool SupportsBuild () + { + return ItemExtension.OnSupportsBuild (); + } + + protected virtual bool OnGetSupportsBuild () + { + return true; + } + + public bool SupportsExecute () + { + return ItemExtension.OnSupportsExecute (); + } + + protected virtual bool OnGetSupportsExecute () + { + return true; + } + + public virtual bool SupportsConfigurations () + { + // TODO NPM: -> extension chain + return SupportsBuild (); + } + + /// <summary> + /// Gets a value indicating whether this project is supported. + /// </summary> + /// <remarks> + /// Unsupported projects are shown in the solution pad, but operations such as building on executing won't be available. + /// </remarks> + public bool IsUnsupportedProject { get; protected set; } + + /// <summary> + /// Gets a message that explain why the project is not supported (when IsUnsupportedProject returns true) + /// </summary> + public string UnsupportedProjectMessage { + get { return IsUnsupportedProject ? (loadError ?? GettextCatalog.GetString ("Unknown project type")) : ""; } + set { loadError = value; } + } + string loadError; + + public bool NeedsBuilding (ConfigurationSelector configuration) + { + return ItemExtension.OnNeedsBuilding (configuration); + } + + internal protected virtual bool OnGetNeedsBuilding (ConfigurationSelector configuration) + { + return false; + } + + public void SetNeedsBuilding (ConfigurationSelector configuration) + { + OnSetNeedsBuilding (configuration); + } + + protected virtual void OnSetNeedsBuilding (ConfigurationSelector configuration) + { + } + /// <summary> /// Builds the solution item /// </summary> /// <param name='monitor'> /// A progress monitor /// </param> - /// <param name='configuration'> + /// <param name='solutionConfiguration'> /// Configuration to use to build the project /// </param> - public BuildResult Build (IProgressMonitor monitor, ConfigurationSelector configuration) + public Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector solutionConfiguration) { - return Build (monitor, configuration, false); + return Build (monitor, solutionConfiguration, false); } - + /// <summary> /// Builds the solution item /// </summary> @@ -548,54 +551,47 @@ namespace MonoDevelop.Projects /// <param name='buildReferences'> /// When set to <c>true</c>, the referenced items will be built before building this item /// </param> - public BuildResult Build (IProgressMonitor monitor, ConfigurationSelector solutionConfiguration, bool buildReferences) + public async Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector solutionConfiguration, bool buildReferences) { ITimeTracker tt = Counters.BuildProjectTimer.BeginTiming ("Building " + Name); try { if (!buildReferences) { - //SolutionFolder's OnRunTarget handles the begin/end task itself, don't duplicate - if (this is SolutionFolder) { - return RunTarget (monitor, ProjectService.BuildTarget, solutionConfiguration); - } - try { - SolutionEntityItem it = this as SolutionEntityItem; - SolutionItemConfiguration iconf = it != null ? it.GetConfiguration (solutionConfiguration) : null; + SolutionItemConfiguration iconf = GetConfiguration (solutionConfiguration); string confName = iconf != null ? iconf.Id : solutionConfiguration.ToString (); monitor.BeginTask (GettextCatalog.GetString ("Building: {0} ({1})", Name, confName), 1); - - // This will end calling OnBuild () - return RunTarget (monitor, ProjectService.BuildTarget, solutionConfiguration); - + + return await InternalBuild (monitor, solutionConfiguration); + } finally { monitor.EndTask (); } } - + // Get a list of all items that need to be built (including this), // and build them in the correct order - - List<SolutionItem> referenced = new List<SolutionItem> ();
- Set<SolutionItem> visited = new Set<SolutionItem> ();
+ + var referenced = new List<SolutionItem> (); + var visited = new Set<SolutionItem> (); GetBuildableReferencedItems (visited, referenced, this, solutionConfiguration); - - ReadOnlyCollection<SolutionItem> sortedReferenced = SolutionFolder.TopologicalSort (referenced, solutionConfiguration); - + + var sortedReferenced = TopologicalSort (referenced, solutionConfiguration); + BuildResult cres = new BuildResult (); cres.BuildCount = 0; - HashSet<SolutionItem> failedItems = new HashSet<SolutionItem> (); - + var failedItems = new HashSet<SolutionItem> (); + monitor.BeginTask (null, sortedReferenced.Count); - foreach (SolutionItem p in sortedReferenced) { + foreach (var p in sortedReferenced) { if (!p.ContainsReferences (failedItems, solutionConfiguration)) { - BuildResult res = p.Build (monitor, solutionConfiguration, false); + BuildResult res = await p.Build (monitor, solutionConfiguration, false); cres.Append (res); if (res.ErrorCount > 0) failedItems.Add (p); } else failedItems.Add (p); monitor.Step (1); - if (monitor.IsCancelRequested) + if (monitor.CancellationToken.IsCancellationRequested) break; } monitor.EndTask (); @@ -604,40 +600,258 @@ namespace MonoDevelop.Projects tt.End (); } } - + + async Task<BuildResult> InternalBuild (ProgressMonitor monitor, ConfigurationSelector configuration) + { + if (IsUnsupportedProject) { + var r = new BuildResult (); + r.AddError (UnsupportedProjectMessage); + return r; + } + + SolutionItemConfiguration conf = GetConfiguration (configuration) as SolutionItemConfiguration; + if (conf != null) { + if (conf.CustomCommands.CanExecute (this, CustomCommandType.BeforeBuild, null, configuration)) { + if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.BeforeBuild, configuration)) { + var r = new BuildResult (); + r.AddError (GettextCatalog.GetString ("Custom command execution failed")); + return r; + } + } + } + + if (monitor.CancellationToken.IsCancellationRequested) + return new BuildResult (new CompilerResults (null), ""); + + BuildResult res = await ItemExtension.OnBuild (monitor, configuration); + + if (conf != null && !monitor.CancellationToken.IsCancellationRequested && !res.Failed) { + if (conf.CustomCommands.CanExecute (this, CustomCommandType.AfterBuild, null, configuration)) { + if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.AfterBuild, configuration)) + res.AddError (GettextCatalog.GetString ("Custom command execution failed")); + } + } + + return res; + } + + /// <summary> + /// Builds the solution item + /// </summary> + /// <param name='monitor'> + /// A progress monitor + /// </param> + /// <param name='configuration'> + /// Configuration to use to build the project + /// </param> + protected virtual Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return Task.FromResult (BuildResult.Success); + } + + void GetBuildableReferencedItems (Set<SolutionItem> visited, List<SolutionItem> referenced, SolutionItem item, ConfigurationSelector configuration) + { + if (!visited.Add(item)) + return; + + referenced.Add (item); + + foreach (var ritem in item.GetReferencedItems (configuration)) + GetBuildableReferencedItems (visited, referenced, ritem, configuration); + } + internal bool ContainsReferences (HashSet<SolutionItem> items, ConfigurationSelector conf) { - foreach (SolutionItem it in GetReferencedItems (conf)) + foreach (var it in GetReferencedItems (conf)) if (items.Contains (it)) return true; return false; } /// <summary> - /// Gets the time of the last build + /// Cleans the files produced by this solution item + /// </summary> + /// <param name='monitor'> + /// A progress monitor + /// </param> + /// <param name='configuration'> + /// Configuration to use to clean the project + /// </param> + public async Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + ITimeTracker tt = Counters.BuildProjectTimer.BeginTiming ("Cleaning " + Name); + try { + try { + SolutionItemConfiguration iconf = GetConfiguration (configuration); + string confName = iconf != null ? iconf.Id : configuration.ToString (); + monitor.BeginTask (GettextCatalog.GetString ("Cleaning: {0} ({1})", Name, confName), 1); + + SolutionItemConfiguration conf = GetConfiguration (configuration); + if (conf != null) { + if (conf.CustomCommands.CanExecute (this, CustomCommandType.BeforeClean, null, configuration)) { + if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.BeforeClean, configuration)) { + var r = new BuildResult (); + r.AddError (GettextCatalog.GetString ("Custom command execution failed")); + return r; + } + } + } + + if (monitor.CancellationToken.IsCancellationRequested) + return BuildResult.Success; + + var res = await ItemExtension.OnClean (monitor, configuration); + + if (conf != null && !monitor.CancellationToken.IsCancellationRequested) { + if (conf.CustomCommands.CanExecute (this, CustomCommandType.AfterClean, null, configuration)) { + if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.AfterClean, configuration)) + res.AddError (GettextCatalog.GetString ("Custom command execution failed")); + } + } + return res; + + } finally { + monitor.EndTask (); + } + } + finally { + tt.End (); + } + } + + /// <summary> + /// Cleans the files produced by this solution item + /// </summary> + /// <param name='monitor'> + /// A progress monitor + /// </param> + /// <param name='configuration'> + /// Configuration to use to clean the project + /// </param> + protected virtual Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return Task.FromResult (BuildResult.Success); + } + + /// <summary> + /// Sorts a collection of solution items, taking into account the dependencies between them /// </summary> /// <returns> - /// The last build time. + /// The sorted collection of items /// </returns> + /// <param name='items'> + /// Items to sort + /// </param> /// <param name='configuration'> - /// Configuration for which to get the last build time. + /// A configuration /// </param> - public DateTime GetLastBuildTime (ConfigurationSelector configuration) + /// <remarks> + /// This methods sorts a collection of items, ensuring that every item is placed after all the items + /// on which it depends. + /// </remarks> + public static ReadOnlyCollection<T> TopologicalSort<T> (IEnumerable<T> items, ConfigurationSelector configuration) where T: SolutionItem + { + IList<T> allItems; + allItems = items as IList<T>; + if (allItems == null) + allItems = new List<T> (items); + + List<T> sortedEntries = new List<T> (); + bool[] inserted = new bool[allItems.Count]; + bool[] triedToInsert = new bool[allItems.Count]; + for (int i = 0; i < allItems.Count; ++i) { + if (!inserted[i]) + Insert<T> (i, allItems, sortedEntries, inserted, triedToInsert, configuration); + } + return sortedEntries.AsReadOnly (); + } + + static void Insert<T> (int index, IList<T> allItems, List<T> sortedItems, bool[] inserted, bool[] triedToInsert, ConfigurationSelector solutionConfiguration) where T: SolutionItem { - return OnGetLastBuildTime (configuration); + if (triedToInsert[index]) { + throw new CyclicDependencyException (); + } + triedToInsert[index] = true; + var insertItem = allItems[index]; + + foreach (var reference in insertItem.GetReferencedItems (solutionConfiguration)) { + for (int j=0; j < allItems.Count; ++j) { + SolutionFolderItem checkItem = allItems[j]; + if (reference == checkItem) { + if (!inserted[j]) + Insert (j, allItems, sortedItems, inserted, triedToInsert, solutionConfiguration); + break; + } + } + } + sortedItems.Add (insertItem); + inserted[index] = true; } - - void GetBuildableReferencedItems (Set<SolutionItem> visited, List<SolutionItem> referenced, SolutionItem item, ConfigurationSelector configuration) - {
- if (!visited.Add(item)) + + /// <summary> + /// Executes this solution item + /// </summary> + /// <param name='monitor'> + /// A progress monitor + /// </param> + /// <param name='context'> + /// An execution context + /// </param> + /// <param name='configuration'> + /// Configuration to use to execute the item + /// </param> + public async Task Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + SolutionItemConfiguration conf = GetConfiguration (configuration) as SolutionItemConfiguration; + if (conf != null) { + ExecutionContext localContext = new ExecutionContext (Runtime.ProcessService.DefaultExecutionHandler, context.ConsoleFactory, context.ExecutionTarget); + + if (conf.CustomCommands.CanExecute (this, CustomCommandType.BeforeExecute, localContext, configuration)) { + if (!await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.BeforeExecute, localContext, configuration)) + return; + } + } + + if (monitor.CancellationToken.IsCancellationRequested) return; - - referenced.Add (item); - foreach (SolutionItem ritem in item.GetReferencedItems (configuration)) - GetBuildableReferencedItems (visited, referenced, ritem, configuration); + await ItemExtension.OnExecute (monitor, context, configuration); + + if (conf != null && !monitor.CancellationToken.IsCancellationRequested) { + ExecutionContext localContext = new ExecutionContext (Runtime.ProcessService.DefaultExecutionHandler, context.ConsoleFactory, context.ExecutionTarget); + + if (conf.CustomCommands.CanExecute (this, CustomCommandType.AfterExecute, localContext, configuration)) + await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.AfterExecute, localContext, configuration); + } } - + + /// <summary> + /// Determines whether this solution item can be executed using the specified context and configuration. + /// </summary> + /// <returns> + /// <c>true</c> if this instance can be executed; otherwise, <c>false</c>. + /// </returns> + /// <param name='context'> + /// An execution context + /// </param> + /// <param name='configuration'> + /// Configuration to use to execute the item + /// </param> + public bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + return !IsUnsupportedProject && ItemExtension.OnGetCanExecute (context, configuration); + } + + async Task DoExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + SolutionItemConfiguration conf = GetConfiguration (configuration) as SolutionItemConfiguration; + if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Execute)) { + await conf.CustomCommands.ExecuteCommand (monitor, this, CustomCommandType.Execute, context, configuration); + return; + } + await OnExecute (monitor, context, configuration); + } + /// <summary> /// Executes this solution item /// </summary> @@ -650,11 +864,19 @@ namespace MonoDevelop.Projects /// <param name='configuration'> /// Configuration to use to execute the item /// </param> - public void Execute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + protected virtual Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { - Services.ProjectService.GetExtensionChain (this).Execute (monitor, this, context, configuration); + return Task.FromResult (0); } - + + bool DoGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + SolutionItemConfiguration conf = GetConfiguration (configuration) as SolutionItemConfiguration; + if (conf != null && conf.CustomCommands.HasCommands (CustomCommandType.Execute)) + return conf.CustomCommands.CanExecute (this, CustomCommandType.Execute, context, configuration); + return OnGetCanExecute (context, configuration); + } + /// <summary> /// Determines whether this solution item can be executed using the specified context and configuration. /// </summary> @@ -667,11 +889,9 @@ namespace MonoDevelop.Projects /// <param name='configuration'> /// Configuration to use to execute the item /// </param> - public bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) + protected virtual bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) { - if (!SupportsExecute ()) - return false; - return Services.ProjectService.GetExtensionChain (this).CanExecute (this, context, configuration); + return ItemExtension.OnGetCanExecute (context, configuration); } /// <summary> @@ -681,7 +901,12 @@ namespace MonoDevelop.Projects /// <param name="configuration">The configuration.</param> public IEnumerable<ExecutionTarget> GetExecutionTargets (ConfigurationSelector configuration) { - return Services.ProjectService.GetExtensionChain (this).GetExecutionTargets (this, configuration); + return ItemExtension.OnGetExecutionTargets (configuration); + } + + protected void NotifyExecutionTargetsChanged () + { + ItemExtension.OnExecutionTargetsChanged (); } public event EventHandler ExecutionTargetsChanged; @@ -691,429 +916,480 @@ namespace MonoDevelop.Projects if (ExecutionTargetsChanged != null) ExecutionTargetsChanged (this, EventArgs.Empty); } - - /// <summary> - /// Checks if this solution item has modified files and has to be built - /// </summary> - /// <returns> - /// <c>true</c> if the solution item has to be built - /// </returns> - /// <param name='configuration'> - /// Configuration for which to do the check - /// </param> - [Obsolete ("This method will be removed in future releases")] - public bool NeedsBuilding (ConfigurationSelector configuration) + + protected virtual Task OnLoad (ProgressMonitor monitor) { - return true; + return Task.FromResult (0); } - internal bool InternalCheckNeedsBuild (ConfigurationSelector configuration) + protected internal virtual Task OnSave (ProgressMonitor monitor) { - using (Counters.NeedsBuildingTimer.BeginTiming ("NeedsBuilding check for " + Name)) { - return Services.ProjectService.GetExtensionChain (this).GetNeedsBuilding (this, configuration); - } + return Task.FromResult (0); } - /// <summary> - /// States whether this solution item needs to be built or not - /// </summary> - /// <param name='value'> - /// Whether this solution item needs to be built or not - /// </param> - /// <param name='configuration'> - /// Configuration for which to set the flag - /// </param> - [Obsolete ("This method will be removed in future releases")] - public void SetNeedsBuilding (bool value, ConfigurationSelector configuration) + public FilePath GetAbsoluteChildPath (FilePath relPath) { - // Nothing to be done. + return relPath.ToAbsolute (BaseDirectory); } - - /// <summary> - /// Gets or sets a value indicating whether this <see cref="MonoDevelop.Projects.SolutionItem"/> needs to be reload due to changes in project or solution file - /// </summary> - /// <value> - /// <c>true</c> if needs reload; otherwise, <c>false</c>. - /// </value> - public virtual bool NeedsReload { - get { - if (ParentSolution != null) - return ParentSolution.NeedsReload; - else - return false; - } - set { - } + + public FilePath GetRelativeChildPath (FilePath absPath) + { + return absPath.ToRelative (BaseDirectory); } - - /// <summary> - /// Registers an internal child item. - /// </summary> - /// <param name='item'> - /// An item - /// </param> - /// <remarks> - /// Some kind of projects may be composed of several child projects. - /// By registering those child projects using this method, the child - /// projects will be plugged into the parent solution infrastructure - /// (so for example, the ParentSolution property for those projects - /// will return the correct value) - /// </remarks> - protected void RegisterInternalChild (SolutionItem item) + + public IEnumerable<FilePath> GetItemFiles (bool includeReferencedFiles) { - if (internalChildren == null) { - internalChildren = new SolutionFolder (); - internalChildren.ParentFolder = parentFolder; - } - internalChildren.Items.Add (item); + return ItemExtension.OnGetItemFiles (includeReferencedFiles); } - - /// <summary> - /// Unregisters an internal child item. - /// </summary> - /// <param name='item'> - /// The item - /// </param> - protected void UnregisterInternalChild (SolutionItem item) + + protected virtual IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) { - if (internalChildren != null) - internalChildren.Items.Remove (item); + List<FilePath> col = FileFormat.Format.GetItemFiles (this); + if (!string.IsNullOrEmpty (FileName) && !col.Contains (FileName)) + col.Add (FileName); + return col; } - - /// <summary> - /// Gets the string tag model description for this solution item - /// </summary> - /// <returns> - /// The string tag model description - /// </returns> - /// <param name='conf'> - /// Configuration for which to get the string tag model description - /// </param> - public virtual StringTagModelDescription GetStringTagModelDescription (ConfigurationSelector conf) + + protected override void OnNameChanged (SolutionItemRenamedEventArgs e) { - StringTagModelDescription model = new StringTagModelDescription (); - model.Add (GetType ()); - model.Add (typeof(Solution)); - return model; + Solution solution = this.ParentSolution; + + if (solution != null) { + foreach (DotNetProject project in solution.GetAllItems<DotNetProject>()) { + if (project == this) + continue; + + project.RenameReferences (e.OldName, e.NewName); + } + } + fileStatusTracker.ResetLoadTimes (); + base.OnNameChanged (e); } - /// <summary> - /// Gets the string tag model for this solution item - /// </summary> - /// <returns> - /// The string tag model - /// </returns> - /// <param name='conf'> - /// Configuration for which to get the string tag model - /// </param> - public virtual StringTagModel GetStringTagModel (ConfigurationSelector conf) + protected virtual void OnSaved (SolutionItemEventArgs args) { - StringTagModel source = new StringTagModel (); - source.Add (this); - if (ParentSolution != null) - source.Add (ParentSolution.GetStringTagModel ()); - return source; + if (Saved != null) + Saved (this, args); } - /// <summary> - /// Sorts a collection of solution items, taking into account the dependencies between them - /// </summary> - /// <returns> - /// The sorted collection of items - /// </returns> - /// <param name='items'> - /// Items to sort - /// </param> - /// <param name='configuration'> - /// A configuration - /// </param> - /// <remarks> - /// This methods sorts a collection of items, ensuring that every item is placed after all the items - /// on which it depends. - /// </remarks> - public static ReadOnlyCollection<T> TopologicalSort<T> (IEnumerable<T> items, ConfigurationSelector configuration) where T: SolutionItem - { - IList<T> allItems; - allItems = items as IList<T>; - if (allItems == null) - allItems = new List<T> (items); - - List<T> sortedEntries = new List<T> (); - bool[] inserted = new bool[allItems.Count]; - bool[] triedToInsert = new bool[allItems.Count]; - for (int i = 0; i < allItems.Count; ++i) { - if (!inserted[i]) - Insert<T> (i, allItems, sortedEntries, inserted, triedToInsert, configuration); + public virtual string[] SupportedPlatforms { + get { + return new string [0]; } - return sortedEntries.AsReadOnly (); } - static void Insert<T> (int index, IList<T> allItems, List<T> sortedItems, bool[] inserted, bool[] triedToInsert, ConfigurationSelector solutionConfiguration) where T: SolutionItem + public virtual SolutionItemConfiguration GetConfiguration (ConfigurationSelector configuration) { - if (triedToInsert[index]) { - throw new CyclicDependencyException (); + return (SolutionItemConfiguration) configuration.GetConfiguration (this) ?? DefaultConfiguration; + } + + ItemConfiguration IConfigurationTarget.DefaultConfiguration { + get { return DefaultConfiguration; } + set { DefaultConfiguration = (SolutionItemConfiguration) value; } + } + + public SolutionItemConfiguration DefaultConfiguration { + get { + if (activeConfiguration == null && configurations.Count > 0) { + return configurations[0]; + } + return activeConfiguration; } - triedToInsert[index] = true; - SolutionItem insertItem = allItems[index]; - - foreach (SolutionItem reference in insertItem.GetReferencedItems (solutionConfiguration)) { - for (int j=0; j < allItems.Count; ++j) { - SolutionItem checkItem = allItems[j]; - if (reference == checkItem) { - if (!inserted[j]) - Insert (j, allItems, sortedItems, inserted, triedToInsert, solutionConfiguration); - break; - } + set { + if (activeConfiguration != value) { + activeConfiguration = value; + NotifyModified ("DefaultConfiguration"); + OnDefaultConfigurationChanged (new ConfigurationEventArgs (this, value)); } } - sortedItems.Add ((T)insertItem); - inserted[index] = true; } - internal virtual IDictionary InternalGetExtendedProperties { + public string DefaultConfigurationId { get { - if (extendedProperties == null) - extendedProperties = new Hashtable (); - return extendedProperties; + if (DefaultConfiguration != null) + return DefaultConfiguration.Id; + else + return null; + } + set { + DefaultConfiguration = GetConfiguration (new ItemConfigurationSelector (value)); } } - void ILoadController.BeginLoad () + public virtual ReadOnlyCollection<string> GetConfigurations () { - loading++; - OnBeginLoad (); + List<string> configs = new List<string> (); + foreach (SolutionItemConfiguration conf in Configurations) + configs.Add (conf.Id); + return configs.AsReadOnly (); } - void ILoadController.EndLoad () - { - loading--; - OnEndLoad (); + [ItemProperty ("Configurations")] + [ItemProperty ("Configuration", ValueType=typeof(SolutionItemConfiguration), Scope="*")] + public SolutionItemConfigurationCollection Configurations { + get { + return configurations; + } } - /// <summary> - /// Called when a load operation for this solution item has started - /// </summary> - protected virtual void OnBeginLoad () - { + IItemConfigurationCollection IConfigurationTarget.Configurations { + get { + return Configurations; + } } - /// <summary> - /// Called when a load operation for this solution item has finished - /// </summary> - protected virtual void OnEndLoad () + public SolutionItemConfiguration AddNewConfiguration (string name) { + SolutionItemConfiguration config = CreateConfiguration (name); + Configurations.Add (config); + return config; } - /// <summary> - /// Notifies that this solution item has been modified - /// </summary> - /// <param name='hint'> - /// Hint about which part of the solution item has been modified. This will typically be the property name. - /// </param> - internal protected void NotifyModified (string hint) + ItemConfiguration IConfigurationTarget.CreateConfiguration (string name) { - if (!Loading) - ItemHandler.OnModified (hint); - OnModified (new SolutionItemModifiedEventArgs (this, hint)); + return CreateConfiguration (name); } - - /// <summary> - /// Raises the modified event. - /// </summary> - /// <param name='args'> - /// Arguments. - /// </param> - protected virtual void OnModified (SolutionItemModifiedEventArgs args) + + public virtual SolutionItemConfiguration CreateConfiguration (string name) { - if (Modified != null && !Disposed) - Modified (this, args); + return ItemExtension.OnCreateConfiguration (name); } - /// <summary> - /// Raises the name changed event. - /// </summary> - /// <param name='e'> - /// Arguments. - /// </param> - protected virtual void OnNameChanged (SolutionItemRenamedEventArgs e) + void OnConfigurationAddedToCollection (object ob, ConfigurationEventArgs args) { - NotifyModified ("Name"); - if (NameChanged != null && !Disposed) - NameChanged (this, e); + NotifyModified ("Configurations"); + OnConfigurationAdded (new ConfigurationEventArgs (this, args.Configuration)); + if (ConfigurationsChanged != null) + ConfigurationsChanged (this, EventArgs.Empty); + if (activeConfiguration == null) + DefaultConfigurationId = args.Configuration.Id; } - /// <summary> - /// Initializes the item handler. - /// </summary> - /// <remarks> - /// This method is called the first time an item handler is requested. - /// Subclasses should override this method use SetItemHandler to - /// assign a handler to this item. - /// </remarks> - protected virtual void InitializeItemHandler () + void OnConfigurationRemovedFromCollection (object ob, ConfigurationEventArgs args) { + if (activeConfiguration == args.Configuration) { + if (Configurations.Count > 0) + DefaultConfiguration = Configurations [0]; + else + DefaultConfiguration = null; + } + NotifyModified ("Configurations"); + OnConfigurationRemoved (new ConfigurationEventArgs (this, args.Configuration)); + if (ConfigurationsChanged != null) + ConfigurationsChanged (this, EventArgs.Empty); } - /// <summary> - /// Runs a build or execution target. - /// </summary> - /// <returns> - /// The result of the operation - /// </returns> - /// <param name='monitor'> - /// A progress monitor - /// </param> - /// <param name='target'> - /// Name of the target - /// </param> - /// <param name='configuration'> - /// Configuration to use to run the target - /// </param> - /// <remarks> - /// Subclasses can override this method to provide a custom implementation of project operations such as - /// build or clean. The default implementation delegates the execution to the more specific OnBuild - /// and OnClean methods, or to the item handler for other targets. - /// </remarks> - internal protected virtual BuildResult OnRunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) + public override StringTagModelDescription GetStringTagModelDescription (ConfigurationSelector conf) { - if (target == ProjectService.BuildTarget) - return OnBuild (monitor, configuration); - else if (target == ProjectService.CleanTarget) { - OnClean (monitor, configuration); - return new BuildResult (); - } - return ItemHandler.RunTarget (monitor, target, configuration) ?? new BuildResult (); + return ItemExtension.OnGetStringTagModelDescription (conf); } - /// <summary> - /// Cleans the files produced by this solution item - /// </summary> - /// <param name='monitor'> - /// A progress monitor - /// </param> - /// <param name='configuration'> - /// Configuration to use to clean the project - /// </param> - protected abstract void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration); + StringTagModelDescription DoGetStringTagModelDescription (ConfigurationSelector conf) + { + StringTagModelDescription model = base.GetStringTagModelDescription (conf); + SolutionItemConfiguration config = GetConfiguration (conf); + if (config != null) + model.Add (config.GetType ()); + else + model.Add (typeof(SolutionItemConfiguration)); + return model; + } + + public override StringTagModel GetStringTagModel (ConfigurationSelector conf) + { + return ItemExtension.OnGetStringTagModel (conf); + } - /// <summary> - /// Builds the solution item - /// </summary> - /// <param name='monitor'> - /// A progress monitor - /// </param> - /// <param name='configuration'> - /// Configuration to use to build the project - /// </param> - protected abstract BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration); + StringTagModel DoGetStringTagModel (ConfigurationSelector conf) + { + StringTagModel source = base.GetStringTagModel (conf); + SolutionItemConfiguration config = GetConfiguration (conf); + if (config != null) + source.Add (config); + return source; + } + + internal protected override DateTime OnGetLastBuildTime (ConfigurationSelector configuration) + { + return ItemExtension.OnGetLastBuildTime (configuration); + } + + DateTime DoGetLastBuildTime (ConfigurationSelector configuration) + { + return base.OnGetLastBuildTime (configuration); + } + + internal protected virtual void OnItemsAdded (IEnumerable<ProjectItem> objs) + { + ItemExtension.OnItemsAdded (objs); + } - /// <summary> - /// Executes this solution item - /// </summary> - /// <param name='monitor'> - /// A progress monitor - /// </param> - /// <param name='context'> - /// An execution context - /// </param> - /// <param name='configuration'> - /// Configuration to use to execute the item - /// </param> - internal protected abstract void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration); + void DoOnItemsAdded (IEnumerable<ProjectItem> objs) + { + NotifyModified ("Items"); + var args = new ProjectItemEventArgs (); + args.AddRange (objs.Select (pi => new ProjectItemEventInfo (this, pi))); + if (ProjectItemAdded != null) + ProjectItemAdded (this, args); + } + + internal protected virtual void OnItemsRemoved (IEnumerable<ProjectItem> objs) + { + ItemExtension.OnItemsRemoved (objs); + } - /// <summary> - /// Checks if this solution item has modified files and has to be built - /// </summary> - /// <returns> - /// <c>true</c> if the solution item has to be built - /// </returns> - /// <param name='configuration'> - /// Configuration for which to do the check - /// </param> - internal protected virtual bool OnGetNeedsBuilding (ConfigurationSelector configuration) + void DoOnItemsRemoved (IEnumerable<ProjectItem> objs) { - return true; + NotifyModified ("Items"); + var args = new ProjectItemEventArgs (); + args.AddRange (objs.Select (pi => new ProjectItemEventInfo (this, pi))); + if (ProjectItemRemoved != null) + ProjectItemRemoved (this, args); + } + + protected virtual void OnDefaultConfigurationChanged (ConfigurationEventArgs args) + { + ItemExtension.OnDefaultConfigurationChanged (args); } - /// <summary> - /// States whether this solution item needs to be built or not - /// </summary> - /// <param name='val'> - /// Whether this solution item needs to be built or not - /// </param> - /// <param name='configuration'> - /// Configuration for which to set the flag - /// </param> - internal protected virtual void OnSetNeedsBuilding (bool val, ConfigurationSelector configuration) + void DoOnDefaultConfigurationChanged (ConfigurationEventArgs args) + { + if (DefaultConfigurationChanged != null) + DefaultConfigurationChanged (this, args); + } + + protected virtual void OnConfigurationAdded (ConfigurationEventArgs args) { + ItemExtension.OnConfigurationAdded (args); } - /// <summary> - /// Gets the time of the last build - /// </summary> - /// <returns> - /// The last build time. - /// </returns> - /// <param name='configuration'> - /// Configuration for which to get the last build time. - /// </param> - internal protected virtual DateTime OnGetLastBuildTime (ConfigurationSelector configuration) + void DoOnConfigurationAdded (ConfigurationEventArgs args) { - return DateTime.MinValue; + if (ConfigurationAdded != null) + ConfigurationAdded (this, args); + } + + protected virtual void OnConfigurationRemoved (ConfigurationEventArgs args) + { + ItemExtension.OnConfigurationRemoved (args); } - internal protected virtual bool OnGetSupportsTarget (string target) + void DoOnConfigurationRemoved (ConfigurationEventArgs args) { - return true; + if (ConfigurationRemoved != null) + ConfigurationRemoved (this, args); } - internal protected virtual bool OnGetSupportsExecute () + protected virtual void OnReloadRequired (SolutionItemEventArgs args) { - return true; + ItemExtension.OnReloadRequired (args); + } + + void DoOnReloadRequired (SolutionItemEventArgs args) + { + fileStatusTracker.FireReloadRequired (args); } - /// <summary> - /// Determines whether this solution item can be executed using the specified context and configuration. - /// </summary> - /// <returns> - /// <c>true</c> if this instance can be executed; otherwise, <c>false</c>. - /// </returns> - /// <param name='context'> - /// An execution context - /// </param> - /// <param name='configuration'> - /// Configuration to use to execute the item - /// </param> - internal protected virtual bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) + protected override void OnBoundToSolution () { - return false; + ParentSolution.SolutionItemRemoved += HandleSolutionItemRemoved; + ParentSolution.SolutionItemAdded += HandleSolutionItemAdded; + ItemExtension.OnBoundToSolution (); } - internal protected virtual IEnumerable<ExecutionTarget> OnGetExecutionTargets (ConfigurationSelector configuration) + void DoOnBoundToSolution () { - yield break; + base.OnBoundToSolution (); } - protected virtual void OnBoundToSolution () + protected override void OnUnboundFromSolution () { + ParentSolution.SolutionItemAdded -= HandleSolutionItemAdded; + ParentSolution.SolutionItemRemoved -= HandleSolutionItemRemoved; + ItemExtension.OnUnboundFromSolution (); } - internal protected virtual object OnGetService (Type t) + void DoOnUnboundFromSolution () { - return ItemHandler.GetService (t); + base.OnUnboundFromSolution (); } - /// <summary> - /// Occurs when the name of the item changes - /// </summary> - public event SolutionItemRenamedEventHandler NameChanged; + + public event SolutionItemEventHandler Saved; - /// <summary> - /// Occurs when the item is modified. - /// </summary> - public event SolutionItemModifiedEventHandler Modified; - } + class DefaultMSBuildItemExtension: SolutionItemExtension + { + internal protected override void OnInitializeFromTemplate (XmlElement template) + { + Item.OnInitializeFromTemplate (template); + } + + internal protected override FilePath OnGetDefaultBaseDirectory () + { + return Item.FileName.IsNullOrEmpty ? FilePath.Empty : Item.FileName.ParentDirectory; + } + + internal protected override IEnumerable<SolutionItem> OnGetReferencedItems (ConfigurationSelector configuration) + { + return Item.OnGetReferencedItems (configuration); + } + + internal protected override StringTagModelDescription OnGetStringTagModelDescription (ConfigurationSelector conf) + { + return Item.DoGetStringTagModelDescription (conf); + } + + internal protected override StringTagModel OnGetStringTagModel (ConfigurationSelector conf) + { + return Item.DoGetStringTagModel (conf); + } + + internal protected override bool OnGetSupportsFormat (FileFormat format) + { + return Item.OnGetSupportsFormat (format); + } + + internal protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) + { + return Item.OnGetItemFiles (includeReferencedFiles); + } + + internal protected override SolutionItemConfiguration OnCreateConfiguration (string name) + { + return new SolutionItemConfiguration (name); + } + + internal protected override string[] SupportedPlatforms { + get { + return new string [0]; + } + } + + internal protected override DateTime OnGetLastBuildTime (ConfigurationSelector configuration) + { + return Item.DoGetLastBuildTime (configuration); + } + + internal protected override Task OnLoad (ProgressMonitor monitor) + { + return Item.OnLoad (monitor); + } + + internal protected override Task OnSave (ProgressMonitor monitor) + { + return Item.DoSave (monitor); + } + + internal protected override bool OnSupportsBuild () + { + return Item.OnGetSupportsBuild (); + } + + internal protected override bool OnSupportsExecute () + { + return Item.OnGetSupportsExecute (); + } + + internal protected override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + return Item.DoExecute (monitor, context, configuration); + } + + internal protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + return Item.DoGetCanExecute (context, configuration); + } + + internal protected override IEnumerable<ExecutionTarget> OnGetExecutionTargets (ConfigurationSelector configuration) + { + yield break; + } + + internal protected override void OnExecutionTargetsChanged () + { + Item.OnExecutionTargetsChanged (); + } + + internal protected override void OnReloadRequired (SolutionItemEventArgs args) + { + Item.DoOnReloadRequired (args); + } + + internal protected override void OnItemsAdded (IEnumerable<ProjectItem> objs) + { + Item.DoOnItemsAdded (objs); + } + + internal protected override void OnItemsRemoved (IEnumerable<ProjectItem> objs) + { + Item.DoOnItemsRemoved (objs); + } + + internal protected override void OnDefaultConfigurationChanged (ConfigurationEventArgs args) + { + Item.DoOnDefaultConfigurationChanged (args); + } + + internal protected override void OnBoundToSolution () + { + Item.DoOnBoundToSolution (); + } + + internal protected override void OnUnboundFromSolution () + { + Item.DoOnUnboundFromSolution (); + } + + internal protected override void OnConfigurationAdded (ConfigurationEventArgs args) + { + Item.DoOnConfigurationAdded (args); + } + + internal protected override void OnConfigurationRemoved (ConfigurationEventArgs args) + { + Item.DoOnConfigurationRemoved (args); + } + + internal protected override void OnModified (SolutionItemModifiedEventArgs args) + { + Item.OnModified (args); + } + + internal protected override void OnNameChanged (SolutionItemRenamedEventArgs e) + { + Item.OnNameChanged (e); + } + + internal protected override IconId StockIcon { + get { + return "md-project"; + } + } + + internal protected override bool ItemFilesChanged { + get { + return Item.BaseItemFilesChanged; + } + } + + internal protected override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return Item.OnBuild (monitor, configuration); + } + + internal protected override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return Item.OnClean (monitor, configuration); + } + + internal protected override bool OnNeedsBuilding (ConfigurationSelector configuration) + { + return Item.OnGetNeedsBuilding (configuration); + } + } + } + [Mono.Addins.Extension] class SolutionItemTagProvider: StringTagProvider<SolutionItem>, IStringTagProvider { @@ -1126,32 +1402,37 @@ namespace MonoDevelop.Projects yield return new StringTagDescription ("AuthorCopyright", "Project Author Copyright"); yield return new StringTagDescription ("AuthorCompany", "Project Author Company"); yield return new StringTagDescription ("AuthorTrademark", "Project Trademark"); + yield return new StringTagDescription ("ProjectFile", "Project File"); } - + public override object GetTagValue (SolutionItem item, string tag) { switch (tag) { - case "ITEMNAME": - case "PROJECTNAME": - return item.Name; - case "AUTHORCOPYRIGHT": - AuthorInformation authorInfo = item.AuthorInformation ?? AuthorInformation.Default; - return authorInfo.Copyright; - case "AUTHORCOMPANY": - authorInfo = item.AuthorInformation ?? AuthorInformation.Default; - return authorInfo.Company; - case "AUTHORTRADEMARK": - authorInfo = item.AuthorInformation ?? AuthorInformation.Default; - return authorInfo.Trademark; - case "AUTHOREMAIL": - authorInfo = item.AuthorInformation ?? AuthorInformation.Default; - return authorInfo.Email; - case "AUTHORNAME": - authorInfo = item.AuthorInformation ?? AuthorInformation.Default; - return authorInfo.Name; - case "ITEMDIR": - case "PROJECTDIR": - return item.BaseDirectory; + case "ITEMNAME": + case "PROJECTNAME": + return item.Name; + case "AUTHORCOPYRIGHT": + AuthorInformation authorInfo = item.AuthorInformation ?? AuthorInformation.Default; + return authorInfo.Copyright; + case "AUTHORCOMPANY": + authorInfo = item.AuthorInformation ?? AuthorInformation.Default; + return authorInfo.Company; + case "AUTHORTRADEMARK": + authorInfo = item.AuthorInformation ?? AuthorInformation.Default; + return authorInfo.Trademark; + case "AUTHOREMAIL": + authorInfo = item.AuthorInformation ?? AuthorInformation.Default; + return authorInfo.Email; + case "AUTHORNAME": + authorInfo = item.AuthorInformation ?? AuthorInformation.Default; + return authorInfo.Name; + case "ITEMDIR": + case "PROJECTDIR": + return item.BaseDirectory; + case "ITEMFILE": + case "PROJECTFILE": + case "PROJECTFILENAME": + return item.FileName; } throw new NotSupportedException (); } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfiguration.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfiguration.cs index 8ec16e80e2..49bdaaa7a0 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfiguration.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfiguration.cs @@ -37,7 +37,7 @@ namespace MonoDevelop.Projects [DataItem (FallbackType=typeof(UnknownConfiguration))] public class SolutionItemConfiguration : ItemConfiguration { - SolutionEntityItem parentItem; + SolutionItem parentItem; public SolutionItemConfiguration () { @@ -47,7 +47,7 @@ namespace MonoDevelop.Projects { } - public SolutionEntityItem ParentItem { + public SolutionItem ParentItem { get { return parentItem; } } @@ -58,7 +58,7 @@ namespace MonoDevelop.Projects ?? configs.FirstOrDefault (c => Name == c.Name && (c.Platform == "" || c.Platform == "Any CPU")); } - internal void SetParentItem (SolutionEntityItem item) + internal void SetParentItem (SolutionItem item) { parentItem = item; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfigurationCollection.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfigurationCollection.cs index a470671b40..0e0a37dd06 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfigurationCollection.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemConfigurationCollection.cs @@ -38,13 +38,13 @@ namespace MonoDevelop.Projects { public class SolutionItemConfigurationCollection : ItemConfigurationCollection<SolutionItemConfiguration> { - SolutionEntityItem parentItem; + SolutionItem parentItem; public SolutionItemConfigurationCollection () { } - internal SolutionItemConfigurationCollection (SolutionEntityItem parentItem) + internal SolutionItemConfigurationCollection (SolutionItem parentItem) { this.parentItem = parentItem; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemEventArgs.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemEventArgs.cs index d9b34ca114..0ca212bfdd 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemEventArgs.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemEventArgs.cs @@ -36,10 +36,10 @@ namespace MonoDevelop.Projects public class SolutionItemEventArgs : EventArgs { - SolutionItem entry; + SolutionFolderItem entry; Solution solution; - public SolutionItem SolutionItem { + public SolutionFolderItem SolutionItem { get { return entry; } @@ -51,12 +51,12 @@ namespace MonoDevelop.Projects } } - public SolutionItemEventArgs (SolutionItem entry) + public SolutionItemEventArgs (SolutionFolderItem entry) { this.entry = entry; } - public SolutionItemEventArgs (SolutionItem entry, Solution solution) + public SolutionItemEventArgs (SolutionFolderItem entry, Solution solution) { this.solution = solution; this.entry = entry; @@ -69,7 +69,7 @@ namespace MonoDevelop.Projects { bool reloading; - public SolutionItemChangeEventArgs (SolutionItem item, Solution parentSolution, bool reloading): base (item, parentSolution) + public SolutionItemChangeEventArgs (SolutionFolderItem item, Solution parentSolution, bool reloading): base (item, parentSolution) { this.reloading = reloading; } @@ -82,14 +82,14 @@ namespace MonoDevelop.Projects /// When Reloading is true, it returns the original solution item that is being reloaded /// </summary> /// <value>The replaced item.</value> - public SolutionItem ReplacedItem { get; internal set; } + public SolutionFolderItem ReplacedItem { get; internal set; } } public delegate void SolutionItemModifiedEventHandler (object sender, SolutionItemModifiedEventArgs e); public class SolutionItemModifiedEventArgs: EventArgsChain<SolutionItemModifiedEventInfo> { - public SolutionItemModifiedEventArgs (SolutionItem item, string hint) + public SolutionItemModifiedEventArgs (SolutionFolderItem item, string hint) { Add (new SolutionItemModifiedEventInfo (item, hint)); } @@ -99,7 +99,7 @@ namespace MonoDevelop.Projects { string hint; - public SolutionItemModifiedEventInfo (SolutionItem item, string hint): base (item) + public SolutionItemModifiedEventInfo (SolutionFolderItem item, string hint): base (item) { this.hint = hint; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemExtension.cs new file mode 100644 index 0000000000..cda42c19c3 --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemExtension.cs @@ -0,0 +1,289 @@ +// +// SolutionItemExtension.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 System.Collections.Generic; +using MonoDevelop.Core; +using MonoDevelop.Core.StringParsing; +using MonoDevelop.Core.Execution; +using System.Xml; +using MonoDevelop.Projects.Formats.MSBuild; +using MonoDevelop.Projects.Extensions; +using System.Threading.Tasks; +using System.Linq; + +namespace MonoDevelop.Projects +{ + public class SolutionItemExtension: WorkspaceObjectExtension, ILoadController + { + SolutionItemExtension next; + + internal string FlavorGuid { get; set; } + + internal protected override void InitializeChain (ChainedExtension next) + { + base.InitializeChain (next); + this.next = FindNextImplementation<SolutionItemExtension> (next); + } + + internal protected override bool SupportsObject (WorkspaceObject item) + { + var p = item as SolutionItem; + if (p == null) + return false; + + return FlavorGuid == null || p.GetItemTypeGuids ().Any (id => id.Equals (FlavorGuid, StringComparison.OrdinalIgnoreCase)); + } + + #region ILoadController implementation + + void ILoadController.BeginLoad () + { + OnBeginLoad (); + } + + void ILoadController.EndLoad () + { + OnEndLoad (); + } + + #endregion + + public SolutionItem Item { + get { return (SolutionItem) Owner; } + } + + internal protected override void Initialize () + { + base.Initialize (); + ProjectExtensionUtil.LoadControl (this); + } + + internal protected virtual void OnInitializeNew (string languageName, ProjectCreateInformation info, XmlElement projectOptions) + { + next.OnInitializeNew (languageName, info, projectOptions); + } + + internal protected virtual void OnInitializeFromTemplate (XmlElement template) + { + next.OnInitializeFromTemplate (template); + } + + #region Project properties + + internal protected virtual IconId StockIcon { + get { + return next.StockIcon; + } + } + #endregion + + #region Project model + + internal protected virtual FilePath OnGetDefaultBaseDirectory () + { + return next.OnGetDefaultBaseDirectory (); + } + + internal protected virtual IEnumerable<SolutionItem> OnGetReferencedItems (ConfigurationSelector configuration) + { + return next.OnGetReferencedItems (configuration); + } + + internal protected virtual StringTagModelDescription OnGetStringTagModelDescription (ConfigurationSelector conf) + { + return next.OnGetStringTagModelDescription (conf); + } + + internal protected virtual StringTagModel OnGetStringTagModel (ConfigurationSelector conf) + { + return next.OnGetStringTagModel (conf); + } + + internal protected virtual bool OnGetSupportsFormat (FileFormat format) + { + return next.OnGetSupportsFormat (format); + } + + internal protected virtual IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) + { + return next.OnGetItemFiles (includeReferencedFiles); + } + + internal protected virtual bool ItemFilesChanged { + get { + return next.ItemFilesChanged; + } + } + + internal protected virtual SolutionItemConfiguration OnCreateConfiguration (string name) + { + return next.OnCreateConfiguration (name); + } + + internal protected virtual string[] SupportedPlatforms { + get { + return next.SupportedPlatforms; + } + } + + #endregion + + #region Building + + internal protected virtual bool OnSupportsBuild () + { + return next.OnSupportsBuild (); + } + + internal protected virtual bool OnSupportsExecute () + { + return next.OnSupportsExecute (); + } + + internal protected virtual Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return next.OnClean (monitor, configuration); + } + + internal protected virtual bool OnNeedsBuilding (ConfigurationSelector configuration) + { + return next.OnNeedsBuilding (configuration); + } + + internal protected virtual Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) + { + return next.OnBuild (monitor, configuration); + } + + internal protected virtual DateTime OnGetLastBuildTime (ConfigurationSelector configuration) + { + return next.OnGetLastBuildTime (configuration); + } + + #endregion + + #region Load / Save + + internal protected virtual Task OnLoad (ProgressMonitor monitor) + { + return next.OnLoad (monitor); + } + + internal protected virtual Task OnSave (ProgressMonitor monitor) + { + return next.OnSave (monitor); + } + + protected virtual void OnBeginLoad () + { + } + + protected virtual void OnEndLoad () + { + } + + #endregion + + #region Execution + + internal protected virtual Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + return next.OnExecute (monitor, context, configuration); + } + + internal protected virtual bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + return next.OnGetCanExecute (context, configuration); + } + + internal protected virtual IEnumerable<ExecutionTarget> OnGetExecutionTargets (ConfigurationSelector configuration) + { + return next.OnGetExecutionTargets (configuration); + } + + internal protected virtual void OnExecutionTargetsChanged () + { + next.OnExecutionTargetsChanged (); + } + + #endregion + + #region Events + + internal protected virtual void OnReloadRequired (SolutionItemEventArgs args) + { + next.OnReloadRequired (args); + } + + internal protected virtual void OnItemsAdded (IEnumerable<ProjectItem> objs) + { + next.OnItemsAdded (objs); + } + + internal protected virtual void OnItemsRemoved (IEnumerable<ProjectItem> objs) + { + next.OnItemsRemoved (objs); + } + + internal protected virtual void OnDefaultConfigurationChanged (ConfigurationEventArgs args) + { + next.OnDefaultConfigurationChanged (args); + } + + internal protected virtual void OnBoundToSolution () + { + next.OnBoundToSolution (); + } + + internal protected virtual void OnUnboundFromSolution () + { + next.OnUnboundFromSolution (); + } + + internal protected virtual void OnConfigurationAdded (ConfigurationEventArgs args) + { + next.OnConfigurationAdded (args); + } + + internal protected virtual void OnConfigurationRemoved (ConfigurationEventArgs args) + { + next.OnConfigurationRemoved (args); + } + + internal protected virtual void OnModified (SolutionItemModifiedEventArgs args) + { + next.OnModified (args); + } + + internal protected virtual void OnNameChanged (SolutionItemRenamedEventArgs e) + { + next.OnNameChanged (e); + } + + #endregion + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemFactory.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemFactory.cs new file mode 100644 index 0000000000..9237ae7de1 --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemFactory.cs @@ -0,0 +1,36 @@ +// +// SolutionItemFactory.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 System.Threading.Tasks; + +namespace MonoDevelop.Projects +{ + public abstract class SolutionItemFactory + { + public abstract Task<SolutionItem> CreateItem (string fileName, string typeGuid); + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemReference.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemReference.cs index d50f388d81..7abc72f987 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemReference.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/SolutionItemReference.cs @@ -43,10 +43,10 @@ namespace MonoDevelop.Projects { } - public SolutionItemReference (SolutionItem item) + public SolutionItemReference (SolutionFolderItem item) { - if (item is SolutionEntityItem) { - path = ((SolutionEntityItem)item).FileName; + if (item is SolutionItem) { + path = ((SolutionItem)item).FileName; } else { path = item.ParentSolution.FileName; if ((item is SolutionFolder) && ((SolutionFolder)item).IsRoot) diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownProject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownProject.cs index 581d8a1b6a..e2142229bd 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownProject.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownProject.cs @@ -1,4 +1,4 @@ -// +// // UnknownProject.cs // // Author: @@ -26,33 +26,31 @@ using System; using MonoDevelop.Core; using System.Collections.Generic; +using System.Threading.Tasks; namespace MonoDevelop.Projects { public class UnknownProject: Project { - string loadError = string.Empty; - bool unloaded; - // Store the file name locally to avoid the file format to change it FilePath fileName; public UnknownProject () { + IsUnsupportedProject = true; NeedsReload = false; - loadError = GettextCatalog.GetString ("Unknown project type"); } public UnknownProject (FilePath file, string loadError): this () { NeedsReload = false; FileName = file; - this.loadError = loadError; + UnsupportedProjectMessage = loadError; } - public override IEnumerable<string> GetProjectTypes () + public override bool SupportsConfigurations () { - yield return ""; + return true; } public override FilePath FileName { @@ -67,55 +65,36 @@ namespace MonoDevelop.Projects } } - - public string LoadError { - get { return unloaded ? GettextCatalog.GetString ("Unavailable") : loadError; } - set { loadError = value; } - } - - public bool UnloadedEntry { - get { return unloaded; } - set { unloaded = value; } - } - - public override string Name { - get { - if (!FileName.IsNullOrEmpty) - return FileName.FileNameWithoutExtension; - else - return GettextCatalog.GetString ("Unknown entry"); - } - set { } + protected override string OnGetName () + { + if (!FileName.IsNullOrEmpty) + return FileName.FileNameWithoutExtension; + else + return GettextCatalog.GetString ("Unknown entry"); } - internal protected override bool OnGetSupportsTarget (string target) + protected override bool OnGetSupportsTarget (string target) { // We can't do anything with unsupported projects, other than display them in the solution pad return false; } - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) { + return Task.FromResult (BuildResult.Success); } - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { var r = new BuildResult (); - r.AddError (loadError); - return r; - } - - protected internal override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) - { - } - - protected internal override bool OnGetNeedsBuilding (ConfigurationSelector configuration) - { - return false; + r.AddError (UnsupportedProjectMessage); + return Task.FromResult (r); } - protected internal override void OnSetNeedsBuilding (bool value, ConfigurationSelector configuration) + protected override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) { + return new Task (delegate { + }); } public override SolutionItemConfiguration CreateConfiguration (string name) diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownSolutionItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownSolutionItem.cs index 08d8697279..9ab6a3102b 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownSolutionItem.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownSolutionItem.cs @@ -28,10 +28,11 @@ using System; using MonoDevelop.Core; +using System.Threading.Tasks; namespace MonoDevelop.Projects { - public class UnknownSolutionItem: SolutionEntityItem + public class UnknownSolutionItem: SolutionItem { string loadError = string.Empty; bool unloaded; @@ -41,7 +42,15 @@ namespace MonoDevelop.Projects public UnknownSolutionItem () { + Initialize (this); NeedsReload = false; + IsUnsupportedProject = true; + } + + public override bool SupportsConfigurations () + { + // The item is unknown, but we still want to read/write its configurations + return true; } public override FilePath FileName { @@ -70,48 +79,30 @@ namespace MonoDevelop.Projects loadError = GettextCatalog.GetString ("Unavailable"); } } - - public override string Name { - get { - if (!FileName.IsNullOrEmpty) - return FileName.FileNameWithoutExtension; - else - return GettextCatalog.GetString ("Unknown entry"); - } - set { } - } - internal protected override bool OnGetSupportsTarget (string target) + protected override string OnGetName () { - return false; + if (!FileName.IsNullOrEmpty) + return FileName.FileNameWithoutExtension; + else + return GettextCatalog.GetString ("Unknown entry"); } - - protected override void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) + + protected override Task<BuildResult> OnClean (ProgressMonitor monitor, ConfigurationSelector configuration) { + return Task.FromResult (BuildResult.Success); } - protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) + protected override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration) { var r = new BuildResult (); r.AddError ("Project unavailable"); - return r; - } - - protected internal override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) - { - } - - protected internal override bool OnGetNeedsBuilding (ConfigurationSelector configuration) - { - return false; - } - - protected internal override void OnSetNeedsBuilding (bool value, ConfigurationSelector configuration) - { + return Task.FromResult (r); } - protected internal override void OnSave (IProgressMonitor monitor) + protected internal override Task OnSave (ProgressMonitor monitor) { + return Task.FromResult (0); } } @@ -119,6 +110,7 @@ namespace MonoDevelop.Projects { public UnloadedSolutionItem () { + Initialize (this); UnloadedEntry = true; } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownWorkspaceItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownWorkspaceItem.cs index a80b990f9c..3c598966a1 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownWorkspaceItem.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/UnknownWorkspaceItem.cs @@ -27,6 +27,7 @@ using System; using MonoDevelop.Core; +using System.Threading.Tasks; namespace MonoDevelop.Projects { @@ -40,6 +41,7 @@ namespace MonoDevelop.Projects public UnknownWorkspaceItem () { NeedsReload = false; + Initialize (this); } public string LoadError { @@ -52,19 +54,17 @@ namespace MonoDevelop.Projects set { unloaded = value; } } - protected internal override void OnSave (IProgressMonitor monitor) + protected internal override Task OnSave (ProgressMonitor monitor) { - Services.ProjectService.InternalWriteWorkspaceItem (monitor, FileName, this); + return Services.ProjectService.InternalWriteWorkspaceItem (monitor, FileName, this); } - public override string Name { - get { - if (!FileName.IsNullOrEmpty) - return FileName.FileNameWithoutExtension; - else - return GettextCatalog.GetString ("Unknown entry"); - } - set { } + protected override string OnGetName () + { + if (!FileName.IsNullOrEmpty) + return FileName.FileNameWithoutExtension; + else + return GettextCatalog.GetString ("Unknown entry"); } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Workspace.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Workspace.cs index a59cdab116..c75837c221 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Workspace.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/Workspace.cs @@ -33,13 +33,20 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using MonoDevelop.Core; using MonoDevelop.Core.Serialization; +using System.Linq; +using System.Threading.Tasks; namespace MonoDevelop.Projects { [ProjectModelDataItem] - public class Workspace: WorkspaceItem, ICustomDataItem + public class Workspace: WorkspaceItem, ICustomDataItem, IBuildTarget { WorkspaceItemCollection items; + + public Workspace () + { + Initialize (this); + } public override void Dispose () { @@ -47,6 +54,37 @@ namespace MonoDevelop.Projects foreach (WorkspaceItem it in Items) it.Dispose (); } + + public async Task<BuildResult> Build (ProgressMonitor monitor, ConfigurationSelector configuration, bool buildReferencedTargets = false) + { + var res = new BuildResult { BuildCount = 0 }; + foreach (var bt in Items.OfType<IBuildTarget> ()) + res.Append (await bt.Build (monitor, configuration)); + return res; + } + + public async Task<BuildResult> Clean (ProgressMonitor monitor, ConfigurationSelector configuration) + { + var res = new BuildResult { BuildCount = 0 }; + foreach (var bt in Items.OfType<IBuildTarget> ()) + res.Append (await bt.Clean (monitor, configuration)); + return res; + } + + public Task Execute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) + { + throw new NotSupportedException (); + } + + public bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) + { + return false; + } + + public bool NeedsBuilding (ConfigurationSelector configuration) + { + return Items.OfType<IBuildTarget> ().Any (t => t.NeedsBuilding (configuration)); + } public override ReadOnlyCollection<string> GetConfigurations () { @@ -67,35 +105,12 @@ namespace MonoDevelop.Projects return items; } } - - public override ReadOnlyCollection<T> GetAllItems<T> () - { - List<T> list = new List<T> (); - GetAllItems<T> (list, this); - return list.AsReadOnly (); - } - - void GetAllItems<T> (List<T> list, WorkspaceItem item) where T: WorkspaceItem + + protected override IEnumerable<WorkspaceObject> OnGetChildren () { - if (item is T) - list.Add ((T) item); - - if (item is Workspace) { - foreach (WorkspaceItem citem in ((Workspace)item).Items) - GetAllItems<T> (list, citem); - } + return Items; } - public override SolutionEntityItem FindSolutionItem (string fileName) - { - foreach (WorkspaceItem it in Items) { - SolutionEntityItem si = it.FindSolutionItem (fileName); - if (si != null) - return si; - } - return null; - }
- [Obsolete("Use GetProjectsContainingFile() (plural) instead")]
public override Project GetProjectContainingFile (FilePath fileName) { @@ -116,7 +131,7 @@ namespace MonoDevelop.Projects } } - public override bool ContainsItem (IWorkspaceObject obj) + public override bool ContainsItem (WorkspaceObject obj) { if (base.ContainsItem (obj)) return true; @@ -129,53 +144,16 @@ namespace MonoDevelop.Projects } - public override ReadOnlyCollection<T> GetAllSolutionItems<T> () - { - List<T> list = new List<T> (); - foreach (WorkspaceItem it in Items) { - list.AddRange (it.GetAllSolutionItems<T> ()); - } - return list.AsReadOnly (); - } - - public override void ConvertToFormat (FileFormat format, bool convertChildren) + public async override Task ConvertToFormat (FileFormat format, bool convertChildren) { - base.ConvertToFormat (format, convertChildren); + await base.ConvertToFormat (format, convertChildren); if (convertChildren) { foreach (WorkspaceItem it in Items) - it.ConvertToFormat (format, true); + await it.ConvertToFormat (format, true); } } - - internal protected override BuildResult OnRunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) - { - BuildResult result = null; - monitor.BeginTask (null, Items.Count); - try { - foreach (WorkspaceItem it in Items) { - BuildResult res = it.RunTarget (monitor, target, configuration); - if (res != null) { - if (result == null) { - result = new BuildResult (); - result.BuildCount = 0; - } - result.Append (res); - } - monitor.Step (1); - } - } finally { - monitor.EndTask (); - } - return result; - } - - protected internal override void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) - { - throw new NotImplementedException (); - } - - public WorkspaceItem ReloadItem (IProgressMonitor monitor, WorkspaceItem item) + public async Task<WorkspaceItem> ReloadItem (ProgressMonitor monitor, WorkspaceItem item) { if (Items.IndexOf (item) == -1) throw new InvalidOperationException ("Item '" + item.Name + "' does not belong to workspace '" + Name + "'"); @@ -184,7 +162,7 @@ namespace MonoDevelop.Projects WorkspaceItem newItem; try { - newItem = Services.ProjectService.ReadWorkspaceItem (monitor, item.FileName); + newItem = await Services.ProjectService.ReadWorkspaceItem (monitor, item.FileName); } catch (Exception ex) { UnknownWorkspaceItem e = new UnknownWorkspaceItem (); e.LoadError = ex.Message; @@ -203,9 +181,9 @@ namespace MonoDevelop.Projects return newItem; }
- public override List<FilePath> GetItemFiles (bool includeReferencedFiles) + protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) {
- List<FilePath> list = base.GetItemFiles (includeReferencedFiles); + List<FilePath> list = base.OnGetItemFiles (includeReferencedFiles).ToList (); if (includeReferencedFiles) { foreach (WorkspaceItem it in Items) list.AddRange (it.GetItemFiles (true)); @@ -271,20 +249,20 @@ namespace MonoDevelop.Projects return data; } - void ICustomDataItem.Deserialize (ITypeSerializer handler, DataCollection data) + async void ICustomDataItem.Deserialize (ITypeSerializer handler, DataCollection data) { DataItem items = (DataItem) data.Extract ("Items"); handler.Deserialize (this, data); - IProgressMonitor monitor = handler.SerializationContext.ProgressMonitor; + ProgressMonitor monitor = handler.SerializationContext.ProgressMonitor; if (monitor == null) - monitor = new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor (); + monitor = new ProgressMonitor (); if (items != null) { string baseDir = Path.GetDirectoryName (handler.SerializationContext.BaseFile); monitor.BeginTask (null, items.ItemData.Count); try { foreach (DataValue item in items.ItemData) { string file = Path.Combine (baseDir, item.Value); - WorkspaceItem it = Services.ProjectService.ReadWorkspaceItem (monitor, file); + WorkspaceItem it = await Services.ProjectService.ReadWorkspaceItem (monitor, file); if (it != null) Items.Add (it); monitor.Step (1); diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceItem.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceItem.cs index 8455a52481..d570d0792e 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceItem.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceItem.cs @@ -41,15 +41,17 @@ using MonoDevelop.Core.Serialization; using MonoDevelop.Core.StringParsing; using MonoDevelop.Core.Execution; using MonoDevelop.Projects.Extensions; +using Mono.Addins; +using System.Linq; +using System.Threading.Tasks; namespace MonoDevelop.Projects { - public abstract class WorkspaceItem : IBuildTarget, IWorkspaceFileObject, ILoadController + public abstract class WorkspaceItem : WorkspaceObject, IWorkspaceFileObject, ILoadController { Workspace parentWorkspace; FileFormat format; internal bool FormatSet; - Hashtable extendedProperties;
FilePath fileName; int loading; PropertyBag userProperties; @@ -57,17 +59,12 @@ namespace MonoDevelop.Projects [ProjectPathItemProperty ("BaseDirectory", DefaultValue=null)]
FilePath baseDirectory; - + public Workspace ParentWorkspace { get { return parentWorkspace; } - internal set { parentWorkspace = value; } - } - - public IDictionary ExtendedProperties { - get { - if (extendedProperties == null) - extendedProperties = new Hashtable (); - return extendedProperties; + internal set { + parentWorkspace = value; + ParentObject = value; } } @@ -80,12 +77,9 @@ namespace MonoDevelop.Projects } } - public virtual string Name { - get {
- if (fileName.IsNullOrEmpty)
- return string.Empty;
- else
- return fileName.FileNameWithoutExtension; + public new string Name { + get { + return base.Name;
} set { if (fileName.IsNullOrEmpty)
@@ -97,6 +91,14 @@ namespace MonoDevelop.Projects } } } + + protected override string OnGetName () + { + if (fileName.IsNullOrEmpty) + return string.Empty; + else + return fileName.FileNameWithoutExtension; + } public virtual FilePath FileName { get { @@ -124,12 +126,9 @@ namespace MonoDevelop.Projects FileName = baseDirectory.Combine (name) + ".x"; } - public FilePath BaseDirectory { + public new FilePath BaseDirectory { get { - if (baseDirectory.IsNull) - return FileName.ParentDirectory.FullPath; - else - return baseDirectory; + return base.BaseDirectory; } set { if (!value.IsNull && !FileName.IsNull && FileName.ParentDirectory.FullPath == value.FullPath) @@ -141,82 +140,64 @@ namespace MonoDevelop.Projects NotifyModified (); } } + + protected override string OnGetBaseDirectory () + { + if (baseDirectory.IsNull) + return FileName.ParentDirectory.FullPath; + else + return baseDirectory; + } - public FilePath ItemDirectory { - get { return FileName.ParentDirectory.FullPath; } + protected override string OnGetItemDirectory () + { + return FileName.ParentDirectory.FullPath; } protected bool Loading { get { return loading > 0; } } - public WorkspaceItem () + protected WorkspaceItem () { - MonoDevelop.Projects.Extensions.ProjectExtensionUtil.LoadControl (this); + ProjectExtensionUtil.LoadControl (this); fileStatusTracker = new FileStatusTracker<WorkspaceItemEventArgs> (this, OnReloadRequired, new WorkspaceItemEventArgs (this)); + Initialize (this); }
- public T GetService<T> () where T: class + WorkspaceItemExtension itemExtension; + + WorkspaceItemExtension ItemExtension { + get { + if (itemExtension == null) + itemExtension = ExtensionChain.GetExtension<WorkspaceItemExtension> (); + return itemExtension; + } + } + + protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions () { - return (T) GetService (typeof(T)); + yield return new DefaultWorkspaceItemExtension (); } - - public virtual object GetService (Type t) + + public IEnumerable<FilePath> GetItemFiles (bool includeReferencedFiles) { - return Services.ProjectService.GetExtensionChain (this).GetService (this, t); + return ItemExtension.GetItemFiles (includeReferencedFiles);
} - public virtual List<FilePath> GetItemFiles (bool includeReferencedFiles) - {
+ protected virtual IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles) + { List<FilePath> col = FileFormat.Format.GetItemFiles (this); if (!string.IsNullOrEmpty (FileName) && !col.Contains (FileName)) col.Add (FileName); return col; } - - public virtual SolutionEntityItem FindSolutionItem (string fileName) - { - return null; - } - - public virtual bool ContainsItem (IWorkspaceObject obj) + + public virtual bool ContainsItem (WorkspaceObject obj) { return this == obj; } - public ReadOnlyCollection<SolutionItem> GetAllSolutionItems () - { - return GetAllSolutionItems<SolutionItem> (); - } - - public virtual ReadOnlyCollection<T> GetAllSolutionItems<T> () where T: SolutionItem - { - return new List<T> ().AsReadOnly (); - } - - public ReadOnlyCollection<Project> GetAllProjects () - { - return GetAllSolutionItems<Project> (); - } - - public virtual ReadOnlyCollection<Solution> GetAllSolutions () - { - return GetAllItems<Solution> (); - } - - public ReadOnlyCollection<WorkspaceItem> GetAllItems () - { - return GetAllItems<WorkspaceItem> (); - } - - public virtual ReadOnlyCollection<T> GetAllItems<T> () where T: WorkspaceItem - { - List<T> list = new List<T> (); - if (this is T) - list.Add ((T)this); - return list.AsReadOnly (); - }
- [Obsolete("Use GetProjectsContainingFile() (plural) instead")]
public virtual Project GetProjectContainingFile (FilePath fileName) { @@ -232,119 +213,12 @@ namespace MonoDevelop.Projects { return new ReadOnlyCollection<string> (new string [0]); } - - protected internal virtual void OnSave (IProgressMonitor monitor) - { - Services.ProjectService.InternalWriteWorkspaceItem (monitor, FileName, this); - } - + internal void SetParentWorkspace (Workspace workspace) { parentWorkspace = workspace; } - - public BuildResult RunTarget (IProgressMonitor monitor, string target, string configuration) - { - return RunTarget (monitor, target, (SolutionConfigurationSelector) configuration); - } - - public BuildResult RunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) - { - return Services.ProjectService.GetExtensionChain (this).RunTarget (monitor, this, target, configuration); - } - - public bool SupportsBuild () - { - return SupportsTarget (ProjectService.BuildTarget); - } - public void Clean (IProgressMonitor monitor, string configuration) - { - Clean (monitor, (SolutionConfigurationSelector) configuration); - } - - public void Clean (IProgressMonitor monitor, ConfigurationSelector configuration) - { - Services.ProjectService.GetExtensionChain (this).RunTarget (monitor, this, ProjectService.CleanTarget, configuration); - } - - public bool SupportsTarget (string target) - { - return Services.ProjectService.GetExtensionChain (this).SupportsTarget (this, target); - } - - public bool SupportsExecute () - { - return Services.ProjectService.GetExtensionChain (this).SupportsExecute (this); - } - - public BuildResult Build (IProgressMonitor monitor, string configuration) - { - return InternalBuild (monitor, (SolutionConfigurationSelector) configuration); - } - - public BuildResult Build (IProgressMonitor monitor, ConfigurationSelector configuration) - { - return InternalBuild (monitor, configuration); - } - - public void Execute (IProgressMonitor monitor, ExecutionContext context, string configuration) - { - Execute (monitor, context, (SolutionConfigurationSelector) configuration); - } - - public void Execute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) - { - Services.ProjectService.GetExtensionChain (this).Execute (monitor, this, context, configuration); - } - - public bool CanExecute (ExecutionContext context, string configuration) - { - return CanExecute (context, (SolutionConfigurationSelector) configuration); - } - - public bool CanExecute (ExecutionContext context, ConfigurationSelector configuration) - { - return Services.ProjectService.GetExtensionChain (this).CanExecute (this, context, configuration); - } - - public IEnumerable<ExecutionTarget> GetExecutionTargets (string configuration) - { - return GetExecutionTargets ((SolutionConfigurationSelector) configuration); - } - - public IEnumerable<ExecutionTarget> GetExecutionTargets (ConfigurationSelector configuration) - { - return Services.ProjectService.GetExtensionChain (this).GetExecutionTargets (this, configuration); - } - - [Obsolete ("This method will be removed in future releases")] - public bool NeedsBuilding (string configuration) - { - return true; - } - - [Obsolete ("This method will be removed in future releases")] - public bool NeedsBuilding (ConfigurationSelector configuration) - { - return true; - } - - [Obsolete ("This method will be removed in future releases")] - public void SetNeedsBuilding (bool value) - { - } - - [Obsolete ("This method will be removed in future releases")] - public void SetNeedsBuilding (bool needsBuilding, string configuration) - { - } - - [Obsolete ("This method will be removed in future releases")] - public void SetNeedsBuilding (bool needsBuilding, ConfigurationSelector configuration) - { - } - public virtual FileFormat FileFormat { get { if (format == null) { @@ -359,17 +233,13 @@ namespace MonoDevelop.Projects return true; } - public virtual void ConvertToFormat (FileFormat format, bool convertChildren) + public virtual Task ConvertToFormat (FileFormat format, bool convertChildren) { FormatSet = true; this.format = format; if (!string.IsNullOrEmpty (FileName)) FileName = format.GetValidFileName (this, FileName); - } - - internal virtual BuildResult InternalBuild (IProgressMonitor monitor, ConfigurationSelector configuration) - { - return Services.ProjectService.GetExtensionChain (this).RunTarget (monitor, this, ProjectService.BuildTarget, configuration); + return Task.FromResult (0); } protected virtual void OnConfigurationsChanged () @@ -380,17 +250,27 @@ namespace MonoDevelop.Projects ParentWorkspace.OnConfigurationsChanged (); }
- public void Save (FilePath fileName, IProgressMonitor monitor) + public void Save (FilePath fileName, ProgressMonitor monitor) { - FileName = fileName; - Save (monitor); + SaveAsync (fileName, monitor).Wait (); } - public void Save (IProgressMonitor monitor) + public Task SaveAsync (FilePath fileName, ProgressMonitor monitor) + { + FileName = fileName; + return SaveAsync (monitor); + } + + public void Save (ProgressMonitor monitor) + { + SaveAsync (monitor).Wait (); + } + + public async Task SaveAsync (ProgressMonitor monitor) { try { fileStatusTracker.BeginSave (); - Services.ProjectService.GetExtensionChain (this).Save (monitor, this); + await ItemExtension.Save (monitor); SaveUserProperties (); OnSaved (new WorkspaceItemEventArgs (this)); @@ -400,7 +280,12 @@ namespace MonoDevelop.Projects } FileService.NotifyFileChanged (FileName); } - + + protected internal virtual Task OnSave (ProgressMonitor monitor) + { + return Services.ProjectService.InternalWriteWorkspaceItem (monitor, FileName, this); + } + public virtual bool NeedsReload { get { return fileStatusTracker.NeedsReload; @@ -416,59 +301,11 @@ namespace MonoDevelop.Projects } } - internal protected virtual BuildResult OnRunTarget (IProgressMonitor monitor, string target, ConfigurationSelector configuration) - { - if (target == ProjectService.BuildTarget) - return OnBuild (monitor, configuration); - else if (target == ProjectService.CleanTarget) { - OnClean (monitor, configuration); - return null; - } - return null; - } - - internal protected virtual bool OnGetSupportsTarget (string target) - { - return true; - } - internal protected virtual bool OnGetSupportsExecute () { return true; } - protected virtual void OnClean (IProgressMonitor monitor, ConfigurationSelector configuration) - { - } - - protected virtual BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) - { - return null; - } - - internal protected virtual void OnExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration) - { - } - - internal protected virtual bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration) - { - return true; - } - - internal protected virtual IEnumerable<ExecutionTarget> OnGetExecutionTargets (ConfigurationSelector configuration) - { - yield break; - } - - internal protected virtual bool OnGetNeedsBuilding (ConfigurationSelector configuration) - { - return true; - } - - internal protected virtual void OnSetNeedsBuilding (bool val, ConfigurationSelector configuration) - { - } - void ILoadController.BeginLoad () { loading++; @@ -571,15 +408,9 @@ namespace MonoDevelop.Projects return absPath.ToRelative (BaseDirectory); } - public virtual void Dispose() + public override void Dispose() { - if (extendedProperties != null) { - foreach (object ob in extendedProperties.Values) { - IDisposable disp = ob as IDisposable; - if (disp != null) - disp.Dispose (); - } - } + base.Dispose (); if (userProperties != null) userProperties.Dispose (); } @@ -592,11 +423,6 @@ namespace MonoDevelop.Projects NameChanged (this, e); } - internal protected virtual object OnGetService (Type t) - { - return null; - } - protected void NotifyModified () { OnModified (new WorkspaceItemEventArgs (this)); @@ -632,6 +458,19 @@ namespace MonoDevelop.Projects fileStatusTracker.ReloadRequired -= value; } }*/ + + internal class DefaultWorkspaceItemExtension: WorkspaceItemExtension + { + internal protected override IEnumerable<FilePath> GetItemFiles (bool includeReferencedFiles) + { + return Item.OnGetItemFiles (includeReferencedFiles); + } + + internal protected override Task Save (ProgressMonitor monitor) + { + return Item.OnSave (monitor); + } + } } class FileStatusTracker<TEventArgs> where TEventArgs:EventArgs diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceItemExtension.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceItemExtension.cs new file mode 100644 index 0000000000..5d3d7643ac --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceItemExtension.cs @@ -0,0 +1,67 @@ +// +// WorkspaceItemExtension.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 System.Collections.Generic; +using MonoDevelop.Core; +using System.Threading.Tasks; + +namespace MonoDevelop.Projects +{ + public class WorkspaceItemExtension: WorkspaceObjectExtension + { + WorkspaceItemExtension next; + + internal protected override bool SupportsObject (WorkspaceObject item) + { + return item is WorkspaceItem; + } + + internal protected override void InitializeChain (ChainedExtension next) + { + this.next = FindNextImplementation<WorkspaceItemExtension> (next); + } + + protected WorkspaceItem Item { + get { return (WorkspaceItem) base.Owner; } + } + + internal protected virtual bool SupportsItem (WorkspaceItem item) + { + return next.SupportsItem (item); + } + + internal protected virtual Task Save (ProgressMonitor monitor) + { + return next.Save (monitor); + } + + internal protected virtual IEnumerable<FilePath> GetItemFiles (bool includeReferencedFiles) + { + return next.GetItemFiles (includeReferencedFiles); + } + } +} + diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceObject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceObject.cs new file mode 100644 index 0000000000..ec464b7769 --- /dev/null +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceObject.cs @@ -0,0 +1,303 @@ +// IWorkspaceObject.cs +// +// Author: +// Lluis Sanchez Gual <lluis@novell.com> +// +// Copyright (c) 2008 Novell, Inc (http://www.novell.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 MonoDevelop.Core; +using MonoDevelop.Core.Serialization; +using System.Collections; +using MonoDevelop.Projects.Extensions; +using Mono.Addins; +using System.Linq; +using System.Threading.Tasks; + + +namespace MonoDevelop.Projects +{ + public abstract class WorkspaceObject: IExtendedDataItem, IFolderItem, IDisposable + { + Hashtable extendedProperties; + bool initializeCalled; + + protected void Initialize<T> (T instance) + { + if (instance.GetType () != typeof(T)) + return; + initializeCalled = true; + OnInitialize (); + InitializeExtensionChain (); + OnExtensionChainInitialized (); + } + + public string Name { + get { return OnGetName (); } + } +
+ public FilePath ItemDirectory { + get { return OnGetItemDirectory (); } + } +
+ public FilePath BaseDirectory { + get { return OnGetBaseDirectory (); } + } + + public WorkspaceObject ParentObject { get; protected set; } + + public IEnumerable<WorkspaceObject> GetChildren () + { + return OnGetChildren (); + } + + public IEnumerable<T> GetAllItems<T> () where T: WorkspaceObject + { + if (this is T) + yield return (T)this; + foreach (var c in OnGetChildren ()) { + foreach (var r in c.GetAllItems<T> ()) + yield return r; + } + } + + /// <summary> + /// Gets extended properties. + /// </summary> + /// <remarks> + /// This dictionary can be used by add-ins to store arbitrary information about this solution item. + /// Keys and values can be of any type. + /// If a value implements IDisposable, the value will be disposed when this item is disposed. + /// </remarks> + public IDictionary ExtendedProperties { + get { + return OnGetExtendedProperties (); + } + } + + /// <summary> + /// Gets a value indicating whether this <see cref="MonoDevelop.Projects.SolutionItem"/> has been disposed. + /// </summary> + /// <value> + /// <c>true</c> if disposed; otherwise, <c>false</c>. + /// </value> + internal protected bool Disposed { get; private set; } + + public virtual void Dispose () + { + if (Disposed) + return; + + Disposed = true; + + if (extensionChain != null) { + extensionChain.Dispose (); + extensionChain = null; + } + + if (extendedProperties != null) { + foreach (object ob in extendedProperties.Values) { + IDisposable disp = ob as IDisposable; + if (disp != null) + disp.Dispose (); + } + extendedProperties = null; + } + } + + /// <summary> + /// Gets a service instance of a given type + /// </summary> + /// <returns> + /// The service. + /// </returns> + /// <typeparam name='T'> + /// Type of the service + /// </typeparam> + /// <remarks> + /// This method looks for an imlpementation of a service of the given type. + /// </remarks> + public T GetService<T> () + { + return (T) GetService (typeof(T)); + } + + /// <summary> + /// Gets a service instance of a given type + /// </summary> + /// <returns> + /// The service. + /// </returns> + /// <param name='t'> + /// Type of the service + /// </param> + /// <remarks> + /// This method looks for an imlpementation of a service of the given type. + /// </remarks> + public object GetService (Type t) + { + return ItemExtension.GetService (t); + } + + /// <summary> + /// Gets a value indicating whether the extension chain for this object has already been created and initialized + /// </summary> + protected bool IsExtensionChainCreated { + get { return extensionChain != null; } + } + + ExtensionChain extensionChain; + protected ExtensionChain ExtensionChain { + get { + if (extensionChain == null) { + if (!initializeCalled) + throw new InvalidOperationException ("The constructor of type " + GetType () + " must call Initialize(this)"); + else + throw new InvalidOperationException ("The extension chain can't be used before OnExtensionChainInitialized() method is called"); + } + return extensionChain; + } + } + + WorkspaceObjectExtension itemExtension; + + WorkspaceObjectExtension ItemExtension { + get { + if (itemExtension == null) + itemExtension = ExtensionChain.GetExtension<WorkspaceObjectExtension> (); + return itemExtension; + } + } + + void InitializeExtensionChain () + { + // Create an initial empty extension chain. This avoid crashes in case a call to SupportsObject ends + // calling methods from the extension + + var tempExtensions = new List<WorkspaceObjectExtension> (); + tempExtensions.AddRange (CreateDefaultExtensions ().Reverse ()); + extensionChain = ExtensionChain.Create (tempExtensions.ToArray ()); + foreach (var e in tempExtensions) + e.Init (this); + + // Collect extensions that support this object + + var extensions = new List<WorkspaceObjectExtension> (); + foreach (ProjectModelExtensionNode node in AddinManager.GetExtensionNodes (ProjectService.ProjectModelExtensionsPath)) { + if (node.CanHandleObject (this)) { + var ext = node.CreateExtension (); + if (ext.SupportsObject (this)) + extensions.Add (ext); + else + ext.Dispose (); + } + } + + foreach (var e in tempExtensions) + e.Dispose (); + + // Now create the final extension chain + + extensions.Reverse (); + extensions.AddRange (CreateDefaultExtensions ().Reverse ()); + extensionChain = ExtensionChain.Create (extensions.ToArray ()); + foreach (var e in extensions) + e.Init (this); + } + + protected virtual IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions () + { + yield return new DefaultWorkspaceObjectExtension (); + } + + /// <summary> + /// Called after the object is created, but before the extension chain has been created. + /// </summary> + protected virtual void OnInitialize () + { + } + + /// <summary> + /// Called when the extension chain for this object has been created. This method can be overriden + /// to do initializations on the object that require access to the extension chain + /// </summary> + protected virtual void OnExtensionChainInitialized () + { + } + + protected virtual IDictionary OnGetExtendedProperties () + { + if (extendedProperties == null) + extendedProperties = new Hashtable (); + return extendedProperties; + } + + protected virtual IEnumerable<WorkspaceObject> OnGetChildren () + { + yield break; + } + + protected virtual object OnGetService (Type t) + { + return t.IsInstanceOfType (this) ? this : null; + } + + protected abstract string OnGetName (); + + protected abstract string OnGetItemDirectory (); + + protected abstract string OnGetBaseDirectory (); + + internal class DefaultWorkspaceObjectExtension: WorkspaceObjectExtension + { + internal protected override object GetService (Type t) + { + return Owner.OnGetService (t); + } + } + } + + public static class WorkspaceObjectExtensions + { + public static T As<T> (this WorkspaceObject ob) where T:class + { + return ob != null ? ob.GetService<T> () : null; + } + } + + public interface IWorkspaceFileObject: IFileItem, IDisposable + { + FileFormat FileFormat { get; } + Task ConvertToFormat (FileFormat format, bool convertChildren); + bool SupportsFormat (FileFormat format);
+ IEnumerable<FilePath> GetItemFiles (bool includeReferencedFiles); + new FilePath FileName { get; set; } + bool NeedsReload { get; set; } + bool ItemFilesChanged { get; } + Task SaveAsync (ProgressMonitor monitor); + string Name { get; set; } + FilePath BaseDirectory { get; } + FilePath ItemDirectory { get; } + } +} diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IWorkspaceObject.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceObjectExtension.cs index 502337e651..541c25ad7c 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/IWorkspaceObject.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Projects/WorkspaceObjectExtension.cs @@ -1,9 +1,10 @@ -// IWorkspaceObject.cs +// +// WorkspaceObjectExtension.cs // // Author: -// Lluis Sanchez Gual <lluis@novell.com> +// Lluis Sanchez Gual <lluis@xamarin.com> // -// Copyright (c) 2008 Novell, Inc (http://www.novell.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 @@ -22,33 +23,41 @@ // 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 MonoDevelop.Core; -using MonoDevelop.Core.Serialization; - +using Mono.Addins; namespace MonoDevelop.Projects { - public interface IWorkspaceObject: IExtendedDataItem, IFolderItem, IDisposable + public class WorkspaceObjectExtension: ChainedExtension { - string Name { get; set; }
- FilePath ItemDirectory { get; }
- new FilePath BaseDirectory { get; set; } - void Save (IProgressMonitor monitor); - } - - public interface IWorkspaceFileObject: IWorkspaceObject, IFileItem - { - FileFormat FileFormat { get; } - void ConvertToFormat (FileFormat format, bool convertChildren); - bool SupportsFormat (FileFormat format);
- List<FilePath> GetItemFiles (bool includeReferencedFiles); - new FilePath FileName { get; set; } - bool NeedsReload { get; set; } - bool ItemFilesChanged { get; } + WorkspaceObjectExtension next; + + internal protected override void InitializeChain (ChainedExtension next) + { + this.next = FindNextImplementation<WorkspaceObjectExtension> (next); + } + + protected WorkspaceObject Owner { get; private set; } + + internal protected virtual bool SupportsObject (WorkspaceObject item) + { + return true; + } + + internal void Init (WorkspaceObject item) + { + Owner = item; + Initialize (); + } + + internal protected virtual void Initialize () + { + } + + internal protected virtual object GetService (Type t) + { + return t.IsInstanceOfType (this) ? this : next.GetService (t); + } } } + |