Welcome to mirror list, hosted at ThFree Co, Russian Federation.

CompiledAssemblyProject.cs « MonoDevelop.Projects « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e506fd1cd472b59d75b9499ea537e46aceba8955 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// 
// CompiledAssemblyProject.cs
//  
// Author:
//       Lluis Sanchez Gual <lluis@novell.com>
// 
// Copyright (c) 2010 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 MonoDevelop.Core;
using MonoDevelop.Core.Assemblies;
using Mono.Cecil;
using MonoDevelop.Core.Execution;
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.MSBuild;

namespace MonoDevelop.Projects
{
	[ExportProjectType ("{8BC9CEB9-8B4A-11D0-8D11-00A0C91BC942}")]
	public class CompiledAssemblyProject: Project, IAssemblyProject
	{
		TargetFramework targetFramework;
		
		public CompiledAssemblyProject ()
		{
			Initialize (this);
			AddNewConfiguration ("Default");
			StockIcon = "md-assembly-project";
		}

		protected override void OnGetTypeTags (HashSet<string> types)
		{
			base.OnGetTypeTags (types);
			types.Add ("CompiledAssembly");
		}

		protected override SolutionItemConfiguration OnCreateConfiguration (string name, ConfigurationKind kind)
		{
			return new ProjectConfiguration (name);
		}
		
		public TargetFramework TargetFramework {
			get {
				return targetFramework;
			}
		}
		
		public MonoDevelop.Core.Assemblies.TargetRuntime TargetRuntime {
			get {
				return Runtime.SystemAssemblyService.DefaultRuntime;
			}
		}
		
		public void LoadFrom (FilePath assemblyPath)
		{
			FileName = assemblyPath;
			
			var tid = Runtime.SystemAssemblyService.GetTargetFrameworkForAssembly (Runtime.SystemAssemblyService.DefaultRuntime, assemblyPath);
			if (tid != null)
				targetFramework = Runtime.SystemAssemblyService.GetTargetFramework (tid);

			using (AssemblyDefinition adef = AssemblyDefinition.ReadAssembly (assemblyPath)) {
				MdbReaderProvider mdbProvider = new MdbReaderProvider ();
				try {
					ISymbolReader reader = mdbProvider.GetSymbolReader (adef.MainModule, assemblyPath);
					adef.MainModule.ReadSymbols (reader);
				} catch {
					// Ignore
				}
				var files = new HashSet<FilePath> ();

				foreach (TypeDefinition type in adef.MainModule.Types) {
					foreach (MethodDefinition met in type.Methods) {
						if (met.HasBody && met.Body.Instructions != null && met.Body.Instructions.Count > 0) {
							SequencePoint sp = met.DebugInformation.GetSequencePoint (met.Body.Instructions [0]);
							if (sp != null)
								files.Add (sp.Document.Url);
						}
					}
				}
			
				FilePath rootPath = FilePath.Empty;
				foreach (FilePath file in files) {
					AddFile (file, BuildAction.Compile);
					if (rootPath.IsNullOrEmpty)
						rootPath = file.ParentDirectory;
					else if (!file.IsChildPathOf (rootPath))
						rootPath = FindCommonRoot (rootPath, file);
				}
				
				if (!rootPath.IsNullOrEmpty)
					BaseDirectory = rootPath;
			}
/*
			foreach (AssemblyNameReference aref in adef.MainModule.AssemblyReferences) {
				if (aref.Name == "mscorlib")
					continue;
				string asm = assemblyPath.ParentDirectory.Combine (aref.Name);
				if (File.Exists (asm + ".dll"))
					References.Add (new ProjectReference (ReferenceType.Assembly, asm + ".dll"));
				else if (File.Exists (asm + ".exe"))
					References.Add (new ProjectReference (ReferenceType.Assembly, asm + ".exe"));
				else
					References.Add (new ProjectReference (ReferenceType.Package, aref.FullName));
			}*/
		}
		
		FilePath FindCommonRoot (FilePath p1, FilePath p2)
		{
			string[] s1 = p1.ToString ().Split (Path.DirectorySeparatorChar);
			string[] s2 = p2.ToString ().Split (Path.DirectorySeparatorChar);
			
			int n;
			for (n=0; n<s1.Length && n<s2.Length && s1[n] == s2[n]; n++);
			return string.Join (Path.DirectorySeparatorChar.ToString (), s1, 0, n);
		}
		
		protected override Task<BuildResult> OnBuild (ProgressMonitor monitor, ConfigurationSelector configuration, OperationContext operationContext)
		{
			return Task.FromResult (BuildResult.CreateSuccess ());
		}
		
		protected async override Task OnExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration, SolutionItemRunConfiguration runConfiguration)
		{
			ProjectConfiguration conf = (ProjectConfiguration) GetConfiguration (configuration);
			monitor.Log.WriteLine (GettextCatalog.GetString ("Running {0} ...", FileName));

			OperationConsole console = conf.ExternalConsole
				? context.ExternalConsoleFactory.CreateConsole (!conf.PauseConsoleOutput, monitor.CancellationToken)
										   : context.ConsoleFactory.CreateConsole (
											   OperationConsoleFactory.CreateConsoleOptions.Default.WithTitle (Path.GetFileName (FileName)), monitor.CancellationToken);
			
			try {
				try {
					ExecutionCommand executionCommand = CreateExecutionCommand (configuration, conf);

					if (!context.ExecutionHandler.CanExecute (executionCommand)) {
						monitor.ReportError (GettextCatalog.GetString ("Can not execute \"{0}\". The selected execution mode is not supported for .NET projects.", FileName), null);
						return;
					}

					ProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute (executionCommand, console);
					using (var stopper = monitor.CancellationToken.Register (asyncOp.Cancel)) {
						await asyncOp.Task;
					}

					monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", asyncOp.ExitCode));
				} finally {
					console.Dispose ();
				}
			} catch (Exception ex) {
				LoggingService.LogError (string.Format ("Cannot execute \"{0}\"", FileName), ex);
				monitor.ReportError (GettextCatalog.GetString ("Cannot execute \"{0}\"", FileName), ex);
			}
		}

		protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration, SolutionItemRunConfiguration runConfiguration)
		{
			ProjectConfiguration config = (ProjectConfiguration) GetConfiguration (configuration);
			if (config == null)
				return false;
			if (!string.Equals (FileName.Extension, ".exe", StringComparison.OrdinalIgnoreCase))
				return false;
			ExecutionCommand cmd = CreateExecutionCommand (configuration, config);
			return context.ExecutionHandler.CanExecute (cmd);
		}

		protected virtual ExecutionCommand CreateExecutionCommand (ConfigurationSelector configSel, ProjectConfiguration configuration)
		{
			DotNetExecutionCommand cmd = new DotNetExecutionCommand (FileName);
			cmd.Arguments = configuration.CommandLineParameters;
			cmd.WorkingDirectory = Path.GetDirectoryName (FileName);
			cmd.EnvironmentVariables = new Dictionary<string, string> (configuration.EnvironmentVariables);
			return cmd;
		}

		internal protected override Task OnSave (ProgressMonitor monitor)
		{
			// Compiled assemblies can't be saved
			return Task.CompletedTask;
		}
	}
	
	public class CompiledAssemblyExtension: WorkspaceObjectReader
	{
		public override bool CanRead (FilePath file, Type expectedType)
		{
			return expectedType.IsAssignableFrom (typeof(SolutionItem)) &&
				               (string.Equals (file.Extension, ".exe", StringComparison.OrdinalIgnoreCase) || string.Equals (file.Extension, ".dll", StringComparison.OrdinalIgnoreCase));
		}

		public override Task<SolutionItem> LoadSolutionItem (ProgressMonitor monitor, SolutionLoadContext ctx, string fileName, MSBuildFileFormat expectedFormat, string typeGuid, string itemGuid)
		{
			CompiledAssemblyProject p = new CompiledAssemblyProject ();
			p.LoadFrom (fileName);
			return Task.FromResult<SolutionItem> (p);
		}
	}
}