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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
|
//
// SharedProject.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
//
// 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.Collections.Generic;
using MonoDevelop.Core;
using System.IO;
using System.Xml;
using MonoDevelop.Projects.Policies;
using System.Threading.Tasks;
using MonoDevelop.Projects.MSBuild;
namespace MonoDevelop.Projects.SharedAssetsProjects
{
[ExportProjectType ("{D954291E-2A0B-460D-934E-DC6B0785DB48}", Extension="shproj", Alias="SharedAssetsProject")]
public sealed class SharedAssetsProject: Project, IDotNetFileContainer
{
Solution currentSolution;
LanguageBinding languageBinding;
string languageName;
FilePath projItemsPath;
MSBuildProject projitemsProject;
HashSet<MSBuildItem> usedMSBuildItems = new HashSet<MSBuildItem> ();
const string CSharptargets = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets";
const string FSharptargets = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.FSharp.targets";
public SharedAssetsProject ()
{
Initialize (this);
}
public SharedAssetsProject (string language): this ()
{
languageName = language;
}
protected override void OnInitializeFromTemplate (ProjectCreateInformation projectCreateInfo, XmlElement projectOptions)
{
base.OnInitializeFromTemplate (projectCreateInfo, projectOptions);
languageName = projectOptions.GetAttribute ("language");
DefaultNamespace = projectCreateInfo.ProjectName;
}
protected override void OnReadProject (ProgressMonitor monitor, MSBuildProject msproject)
{
base.OnReadProject (monitor, msproject);
var import = msproject.Imports.FirstOrDefault (im => im.Label == "Shared");
if (import == null)
return;
// TODO: load the type from msbuild
foreach (var item in msproject.Imports) {
if (item.Project.Equals (CSharptargets, StringComparison.OrdinalIgnoreCase)) {
LanguageName = "C#";
break;
}
if (item.Project.Equals (FSharptargets, StringComparison.OrdinalIgnoreCase)) {
LanguageName = "F#";
break;
}
}
//If for some reason the language name is empty default it to C#
if (String.IsNullOrEmpty(LanguageName))
LanguageName = "C#";
projItemsPath = MSBuildProjectService.FromMSBuildPath (msproject.BaseDirectory, import.Project);
MSBuildProject p = new MSBuildProject (msproject.EngineManager);
p.Load (projItemsPath);
p.Evaluate ();
var cp = p.PropertyGroups.FirstOrDefault (g => g.Label == "Configuration");
if (cp != null)
DefaultNamespace = cp.GetValue ("Import_RootNamespace");
LoadProjectItems (p, ProjectItemFlags.None, usedMSBuildItems);
projitemsProject = p;
}
internal override void SaveProjectItems (ProgressMonitor monitor, MSBuildProject msproject, HashSet<MSBuildItem> loadedItems, string pathPrefix)
{
// Save project items in the .projitems file
base.SaveProjectItems (monitor, projitemsProject, usedMSBuildItems, "$(MSBuildThisFileDirectory)");
}
protected override void OnWriteProject (ProgressMonitor monitor, MonoDevelop.Projects.MSBuild.MSBuildProject msproject)
{
if (projItemsPath == FilePath.Null)
projItemsPath = Path.ChangeExtension (FileName, ".projitems");
if (projitemsProject == null) {
projitemsProject = new MSBuildProject (msproject.EngineManager);
projitemsProject.FileName = projItemsPath;
var grp = projitemsProject.GetGlobalPropertyGroup ();
if (grp == null)
grp = projitemsProject.AddNewPropertyGroup (false);
grp.SetValue ("MSBuildAllProjects", "$(MSBuildAllProjects);$(MSBuildThisFileFullPath)");
grp.SetValue ("HasSharedItems", true);
grp.SetValue ("SharedGUID", ItemId, preserveExistingCase:true);
}
IMSBuildPropertySet configGrp = projitemsProject.PropertyGroups.FirstOrDefault (g => g.Label == "Configuration");
if (configGrp == null) {
configGrp = projitemsProject.AddNewPropertyGroup (true);
configGrp.Label = "Configuration";
}
configGrp.SetValue ("Import_RootNamespace", DefaultNamespace);
base.OnWriteProject (monitor, msproject);
var newProject = FileName == null || !File.Exists (FileName);
if (newProject) {
var grp = msproject.GetGlobalPropertyGroup ();
if (grp == null)
grp = msproject.AddNewPropertyGroup (false);
grp.SetValue ("ProjectGuid", ItemId, preserveExistingCase:true);
var import = msproject.AddNewImport (@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props");
import.Condition = @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')";
msproject.AddNewImport (@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props");
msproject.AddNewImport (@"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props");
import = msproject.AddNewImport (Path.ChangeExtension (FileName.FileName, ".projitems"));
import.Label = "Shared";
if (LanguageName.Equals("C#", StringComparison.OrdinalIgnoreCase)) {
msproject.AddNewImport (CSharptargets);
}
else if (LanguageName.Equals("F#", StringComparison.OrdinalIgnoreCase)) {
msproject.AddNewImport (FSharptargets);
}
} else {
msproject.Load (FileName);
}
// 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";
projitemsProject.Save (projItemsPath);
}
protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles)
{
var list = base.OnGetItemFiles (includeReferencedFiles).ToList ();
if (!string.IsNullOrEmpty (FileName))
list.Add (ProjItemsPath);
return list;
}
public string LanguageName {
get { return languageName; }
set { languageName = value; }
}
public string DefaultNamespace { get; set; }
public FilePath ProjItemsPath {
get {
return !projItemsPath.IsNull ? projItemsPath : FileName.ChangeExtension (".projitems");
}
set {
projItemsPath = value;
}
}
protected override void OnGetTypeTags (HashSet<string> types)
{
types.Add ("SharedAssets");
types.Add ("DotNet");
}
protected override string[] OnGetSupportedLanguages ()
{
return new [] { "", languageName };
}
public LanguageBinding LanguageBinding {
get {
if (languageBinding == null)
languageBinding = LanguageBindingService.GetBindingPerLanguageName (languageName);
return languageBinding;
}
}
protected override bool OnGetIsCompileable (string fileName)
{
return LanguageBinding.IsSourceCodeFile (fileName);
}
protected override Task<BuildResult> OnBuild (MonoDevelop.Core.ProgressMonitor monitor, ConfigurationSelector configuration, OperationContext operationContext)
{
return Task.FromResult (BuildResult.CreateSuccess ());
}
protected override bool OnGetSupportsTarget (string target)
{
return false;
}
protected override ProjectFeatures OnGetSupportedFeatures ()
{
return ProjectFeatures.None;
}
protected override bool OnFastCheckNeedsBuild (ConfigurationSelector configuration)
{
return false;
}
protected override IEnumerable<string> OnGetStandardBuildActions ()
{
return BuildAction.DotNetActions;
}
protected override IList<string> OnGetCommonBuildActions ()
{
return BuildAction.DotNetCommonActions;
}
/// <summary>
/// Gets the default namespace for the file, according to the naming policy.
/// </summary>
/// <remarks>Always returns a valid namespace, even if the fileName is null.</remarks>
public string GetDefaultNamespace (string fileName, bool useVisualStudioNamingPolicy = false)
{
return DotNetProject.GetDefaultNamespace (this, DefaultNamespace, fileName, useVisualStudioNamingPolicy);
}
protected override void OnBoundToSolution ()
{
if (currentSolution != null)
DisconnectFromSolution ();
base.OnBoundToSolution ();
ParentSolution.ReferenceAddedToProject += HandleReferenceAddedToProject;
ParentSolution.ReferenceRemovedFromProject += HandleReferenceRemovedFromProject;
ParentSolution.SolutionItemAdded += HandleSolutionItemAdded;
currentSolution = ParentSolution;
// Maybe there is a project that is already referencing this one. It may happen when creating a solution
// from a template
foreach (var p in ParentSolution.GetAllItems<DotNetProject> ())
ProcessProject (p);
}
void HandleSolutionItemAdded (object sender, SolutionItemChangeEventArgs e)
{
var p = e.SolutionItem as DotNetProject;
if (p != null)
// Maybe the new project already contains a reference to this shared project
ProcessProject (p);
var folder = e.SolutionItem as SolutionFolder;
if (folder != null) {
foreach (var proj in folder.GetAllItems<DotNetProject>()) {
ProcessProject (proj);
}
}
}
protected override void OnDispose ()
{
if (projitemsProject != null)
projitemsProject.Dispose ();
DisconnectFromSolution ();
base.OnDispose ();
}
void DisconnectFromSolution ()
{
if (currentSolution != null) {
currentSolution.ReferenceAddedToProject -= HandleReferenceAddedToProject;
currentSolution.ReferenceRemovedFromProject -= HandleReferenceRemovedFromProject;
currentSolution.SolutionItemAdded -= HandleSolutionItemAdded;
currentSolution = null;
}
}
void HandleReferenceRemovedFromProject (object sender, ProjectReferenceEventArgs e)
{
if (e.ProjectReference.ReferenceType == ReferenceType.Project && e.ProjectReference.Reference == Name) {
foreach (var f in Files) {
var pf = e.Project.GetProjectFile (f.FilePath);
if ((pf.Flags & ProjectItemFlags.DontPersist) != 0)
e.Project.Files.Remove (pf.FilePath);
}
}
}
void HandleReferenceAddedToProject (object sender, ProjectReferenceEventArgs e)
{
if (e.ProjectReference.ReferenceType == ReferenceType.Project && e.ProjectReference.Reference == Name) {
ProcessNewReference (e.ProjectReference);
}
}
void ProcessProject (DotNetProject p)
{
// When the projitems file name doesn't match the shproj file name, the reference we add to the referencing projects
// uses the projitems name, not the shproj name. Here we detect such case and re-add the references using the correct name
var referencesToFix = p.References.Where (r => r.GetItemsProjectPath () == ProjItemsPath && r.Reference != Name).ToList ();
foreach (var r in referencesToFix) {
p.References.Remove (r);
p.References.Add (ProjectReference.CreateProjectReference (this));
}
foreach (var pref in p.References.Where (r => r.ReferenceType == ReferenceType.Project && r.Reference == Name))
ProcessNewReference (pref);
}
void ProcessNewReference (ProjectReference pref)
{
pref.Flags = ProjectItemFlags.DontPersist;
pref.SetItemsProjectPath (ProjItemsPath);
foreach (var f in Files) {
if (pref.OwnerProject.Files.GetFile (f.FilePath) == null && f.Subtype != Subtype.Directory) {
var cf = (ProjectFile)f.Clone ();
cf.Flags |= ProjectItemFlags.DontPersist | ProjectItemFlags.Hidden;
pref.OwnerProject.Files.Add (cf);
}
}
}
protected override void OnFilePropertyChangedInProject (ProjectFileEventArgs e)
{
base.OnFilePropertyChangedInProject (e);
foreach (var p in GetReferencingProjects ()) {
foreach (var f in e) {
if (f.ProjectFile.Subtype == Subtype.Directory)
continue;
var pf = (ProjectFile) f.ProjectFile.Clone ();
pf.Flags |= ProjectItemFlags.DontPersist | ProjectItemFlags.Hidden;
p.Files.Remove (pf.FilePath);
p.Files.Add (pf);
}
}
}
protected override void OnFileAddedToProject (ProjectFileEventArgs e)
{
base.OnFileAddedToProject (e);
foreach (var p in GetReferencingProjects ()) {
foreach (var f in e) {
if (f.ProjectFile.Subtype != Subtype.Directory && p.Files.GetFile (f.ProjectFile.FilePath) == null) {
var pf = (ProjectFile)f.ProjectFile.Clone ();
pf.Flags |= ProjectItemFlags.DontPersist | ProjectItemFlags.Hidden;
p.Files.Add (pf);
}
}
}
}
protected override void OnFileRemovedFromProject (ProjectFileEventArgs e)
{
base.OnFileRemovedFromProject (e);
foreach (var p in GetReferencingProjects ()) {
foreach (var f in e) {
if (f.ProjectFile.Subtype != Subtype.Directory)
p.Files.Remove (f.ProjectFile.FilePath);
}
}
}
protected override void OnFileRenamedInProject (ProjectFileRenamedEventArgs e)
{
base.OnFileRenamedInProject (e);
foreach (var p in GetReferencingProjects ()) {
foreach (var f in e) {
if (f.ProjectFile.Subtype == Subtype.Directory)
continue;
var pf = (ProjectFile) f.ProjectFile.Clone ();
p.Files.Remove (f.OldName);
pf.Flags |= ProjectItemFlags.DontPersist | ProjectItemFlags.Hidden;
p.Files.Add (pf);
}
}
}
IEnumerable<DotNetProject> GetReferencingProjects ()
{
if (ParentSolution == null)
return new DotNetProject[0];
return ParentSolution.GetAllItems<DotNetProject> ().Where (p => p.References.Any (r => r.GetItemsProjectPath () != null));
}
}
internal static class SharedAssetsProjectExtensions
{
public static string GetItemsProjectPath (this ProjectReference r)
{
return (string) r.ExtendedProperties ["MSBuild.SharedAssetsProject"];
}
public static void SetItemsProjectPath (this ProjectReference r, string path)
{
r.ExtendedProperties ["MSBuild.SharedAssetsProject"] = path;
}
}
}
|