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

TemplatingService.cs « MonoDevelop.Ide.Templates « MonoDevelop.Ide « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 71c4101a4960a0125d89992ea5aea54911e0bfa9 (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
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
//
// TemplatingService.cs
//
// Author:
//       Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Addins;
using MonoDevelop.Core;
using MonoDevelop.Ide.Codons;
using MonoDevelop.Ide.Desktop;
using MonoDevelop.Ide.Projects;
using MonoDevelop.Projects;
using Xwt.Drawing;

namespace MonoDevelop.Ide.Templates
{
	public class TemplatingService
	{
		List<TemplateCategory> projectTemplateCategories = new List<TemplateCategory> ();
		List<IProjectTemplatingProvider> templateProviders = new List<IProjectTemplatingProvider> ();
		List<TemplateWizard> projectTemplateWizards = new List<TemplateWizard> ();
		List<ImageCodon> projectTemplateImages = new List<ImageCodon> ();

		MicrosoftTemplateEngineItemTemplatingProvider itemTemplatingProvider;

		public TemplatingService ()
		{
			RecentTemplates = new RecentTemplates ();
			itemTemplatingProvider = new MicrosoftTemplateEngineItemTemplatingProvider ();
			AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Ide/ProjectTemplateCategories", OnTemplateCategoriesChanged);
			AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Ide/ProjectTemplatingProviders", OnTemplatingProvidersChanged);
			AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Ide/ProjectTemplateWizards", OnProjectTemplateWizardsChanged);
			AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Ide/TemplateImages", OnTemplateImagesChanged);
		}

		void OnTemplateCategoriesChanged (object sender, ExtensionNodeEventArgs args)
		{
			var codon = (TemplateCategoryCodon)args.ExtensionNode;
			if (args.Change == ExtensionChange.Add) {
				projectTemplateCategories.Add (codon.ToTopLevelTemplateCategory ());
			} else {
				projectTemplateCategories.RemoveAll (category => category.Id == codon.Id);
			}
		}

		void OnTemplatingProvidersChanged (object sender, ExtensionNodeEventArgs args)
		{
			var provider = args.ExtensionObject as IProjectTemplatingProvider;
			if (args.Change == ExtensionChange.Add) {
				templateProviders.Add (provider);
			} else {
				templateProviders.Remove (provider);
			}
		}

		void OnProjectTemplateWizardsChanged (object sender, ExtensionNodeEventArgs args)
		{
			var wizard = args.ExtensionObject as TemplateWizard;
			if (args.Change == ExtensionChange.Add) {
				projectTemplateWizards.Add (wizard);
			} else {
				projectTemplateWizards.Remove (wizard);
			}
		}

		void OnTemplateImagesChanged (object sender, ExtensionNodeEventArgs args)
		{
			var codon = args.ExtensionNode as ImageCodon;
			if (args.Change == ExtensionChange.Add) {
				projectTemplateImages.Add (codon);
			} else {
				projectTemplateImages.Remove (codon);
			}
		}

		public IEnumerable<TemplateCategory> GetProjectTemplateCategories ()
		{
			return GetProjectTemplateCategories (solutionTemplate => true);
		}

		public IEnumerable<TemplateCategory> GetProjectTemplateCategories (Predicate<SolutionTemplate> match)
		{
			List<Exception> errors = null;
			var templateCategorizer = new ProjectTemplateCategorizer (projectTemplateCategories, match);
			foreach (IProjectTemplatingProvider provider in templateProviders) {
				try {
					templateCategorizer.CategorizeTemplates (provider.GetTemplates ());
				} catch (Exception ex) {
					LoggingService.LogError ("Unable to load templates from provider: " + provider.GetType ().FullName, ex);
					if (errors == null)
						errors = new List<Exception> ();
					errors.Add (ex);
				}
			}

			if (errors != null) {
				ShowProjectTemplateLoadError (errors);
			}

			return templateCategorizer.GetCategorizedTemplates ();
		}

		static void ShowProjectTemplateLoadError (IEnumerable<Exception> errors)
		{
			var message = new StringBuilder ();
			message.AppendLine (GettextCatalog.GetString ("Unable to load project templates."));
			foreach (var error in errors)
				message.AppendLine (error.Message);

			MessageService.ShowError (message.ToString ());
		}

		internal static SolutionTemplate GetTemplate (IEnumerable<TemplateCategory> categories, string templateId)
		{
			return GetTemplate (
				categories,
				template => template.Id == templateId,
				category => true,
				category => true);
		}

		internal static SolutionTemplate GetTemplate (
			IEnumerable<TemplateCategory> categories,
			Func<SolutionTemplate, bool> isTemplateMatch,
			Func<TemplateCategory, bool> isTopLevelCategoryMatch,
			Func<TemplateCategory, bool> isSecondLevelCategoryMatch)
		{
			Predicate<SolutionTemplate> predicate = (t) => isTemplateMatch (t);
			foreach (TemplateCategory topLevelCategory in categories.Where (isTopLevelCategoryMatch)) {
				foreach (TemplateCategory secondLevelCategory in topLevelCategory.Categories.Where (isSecondLevelCategoryMatch)) {
					foreach (TemplateCategory thirdLevelCategory in secondLevelCategory.Categories) {
						foreach (SolutionTemplate template in thirdLevelCategory.Templates) {
							if (isTemplateMatch (template))
								return template;
							else {
								var groupedTemplate = template.GetTemplate (predicate);
								if (groupedTemplate != null)
									return groupedTemplate;
							}
						}
					}
				}
			}
			return null;
		}

		public async Task<ProcessedTemplateResult> ProcessTemplate (SolutionTemplate template, NewProjectConfiguration config, SolutionFolder parentFolder)
		{
			IProjectTemplatingProvider provider = GetTemplatingProviderForTemplate (template);
			if (provider != null) {
				var result = await provider.ProcessTemplate (template, config, parentFolder);
				if (result.WorkspaceItems.Any ())
					RecentTemplates.AddTemplate (template);
				return result;
			}
			return null;
		}

		IProjectTemplatingProvider GetTemplatingProviderForTemplate (SolutionTemplate template)
		{
			return templateProviders.FirstOrDefault (provider => provider.CanProcessTemplate (template));
		}

		public TemplateWizard GetWizard (string id)
		{
			return projectTemplateWizards.FirstOrDefault (wizard => wizard.Id == id);
		}

		public Image LoadTemplateImage (string imageId)
		{
			ImageCodon imageCodon = projectTemplateImages.FirstOrDefault (codon => codon.Id == imageId);

			if (imageCodon != null) {
				return imageCodon.Addin.GetImageResource (imageCodon.Resource);
			}
			return null;
		}

		public IEnumerable<ItemTemplate> GetItemTemplates ()
		{
			return itemTemplatingProvider.GetTemplates ();
		}

		public SolutionTemplate GetSolutionTemplate (string templateId)
		{
			var categories = GetProjectTemplateCategories (template => template.Id == templateId);
			return GetTemplate (categories, templateId);
		}

		public IEnumerable<ItemTemplate> GetItemTemplates (Predicate<ItemTemplate> match)
		{
			return GetItemTemplates ().Where (template => match (template));
		}

		public Task ProcessTemplate (ItemTemplate template, Project project, NewItemConfiguration config)
		{
			return itemTemplatingProvider.ProcessTemplate (template, project, config);
		}

		public RecentTemplates RecentTemplates { get; private set; }
	}

	public class RecentTemplates
	{
		RecentFileStorage recentTemplates;

		const string templateUriScheme = "monodevelop+template://";
		const string templateGroup = "MonoDevelop Templates";

		const int ItemLimit = 25;

		public RecentTemplates () : this (UserProfile.Current.LocalConfigDir.Combine ("RecentlyUsedTemplates.xml"))
		{
		}

		public RecentTemplates (string storageFile)
		{
			recentTemplates = new RecentFileStorage (storageFile);
		}

		public event EventHandler Changed {
			add { recentTemplates.RecentFilesChanged += value; }
			remove { recentTemplates.RecentFilesChanged -= value; }
		}

		public IList<SolutionTemplate> GetTemplates ()
		{
			var categories = IdeServices.TemplatingService.GetProjectTemplateCategories ();
			return GetTemplates (categories);
		}

		internal IList<SolutionTemplate> GetTemplates (IEnumerable<TemplateCategory> categories)
		{
			try {
				var gp = recentTemplates.GetItemsInGroup (templateGroup);
				return gp.Select (item => FromRecentItem (categories, item)).Where (t => t != null).ToList ();
			} catch (Exception e) {
				LoggingService.LogError ("Can't get recent templates list.", e);
				return new List<SolutionTemplate> ();
			}
		}

		public void Clear ()
		{
			try {
				recentTemplates.ClearGroup (templateGroup);
			} catch (Exception e) {
				LoggingService.LogError ("Can't clear recent templates list.", e);
			}
		}

		public void AddTemplate (SolutionTemplate template)
		{
			try {
				if (template.HasGroupId)
					RemoveTemplateFromSameGroup (template);
				var recentItem = CreateRecentItem (template);
				recentTemplates.AddWithLimit (recentItem, templateGroup, ItemLimit);
			} catch (Exception e) {
				LoggingService.LogError ("Failed to add item to recent templates list.", e);
			}
		}

		/// <summary>
		/// Removes any recent templates from the same group if it has the same language.
		/// Different languages for the same group can exist separately in the recent project
		/// templates list.
		/// </summary>
		void RemoveTemplateFromSameGroup (SolutionTemplate template)
		{
			foreach (var groupTemplate in template.GetGroupedTemplates ()) {
				if (groupTemplate.Language == template.Language) {
					var recentItem = CreateRecentItem (groupTemplate);
					recentTemplates.RemoveItem (recentItem);
				}
			}
		}

		RecentItem CreateRecentItem (SolutionTemplate template)
		{
			var mime = "application/vnd.monodevelop.template";
			var uri = templateUriScheme ;
			var categoryPath = template.Category;
			if (!string.IsNullOrEmpty (categoryPath))
				uri += categoryPath + "/";
			uri += template.Id;
			return new RecentItem (uri, mime, templateGroup) { Private = template.Name };
		}

		SolutionTemplate FromRecentItem (IEnumerable<TemplateCategory> categories, RecentItem item)
		{
			var templatePath = item.Uri.StartsWith (templateUriScheme, StringComparison.Ordinal) ? item.Uri.Substring (templateUriScheme.Length) : item.Uri;
			var parts = templatePath.Split ('/');
			var templateId = parts [parts.Length - 1];
			SolutionTemplate recentTemplate = null;

			if (parts.Length > 1)
				recentTemplate = TemplatingService.GetTemplate (
					categories,
					(template) => template.Id == templateId,
					(category) => parts.Length > 1 ? category.Id == parts[0] : true,
					(category) => parts.Length > 2 ? category.Id == parts[1] : true
				);

			// fallback to global template lookup if no category matched
			// in this case the category is not guaranteed if a template is listed in more than one category
			if (recentTemplate == null)
				recentTemplate = TemplatingService.GetTemplate (categories, templateId);
			return recentTemplate;
		}

		public void Dispose ()
		{
			recentTemplates.Dispose ();
			recentTemplates = null;
		}
	}
}