~do-core/do/test-trunk

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
// PluginManager.cs
//
// GNOME Do is the legal property of its developers. Please refer to the
// COPYRIGHT file distributed with this
// source distribution.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.IO;
using System.Xml;
using System.Linq;
using System.Collections.Generic;

using Mono.Unix;
using Mono.Addins;
using Mono.Addins.Gui;
using Mono.Addins.Setup;

using Do.UI;
using Do.Platform;
using Do.Platform.Linux;
using Do.Universe;
using Do.Interface;
using Do.Core.Addins;

namespace Do.Core
{

	/// <summary>
	/// PluginManager serves as Do's primary interface to Mono.Addins.
	/// </summary>
	public class PluginManager
	{
		const string DefaultPluginIcon = "folder_tar";
		
		static IEnumerable<string> ExtensionPaths = new [] { "/Do/ItemSource", "/Do/Action" };

		public static readonly IEnumerable<AddinClassifier> Classifiers =
			new AddinClassifier [] {
				new OfficialAddinClassifier (),
				new CommunityAddinClassifier (),
			    new DockletAddinClassifier (),
				new GreedyAddinClassifier (),
			};
			
		/// <summary>
		/// Performs plugin system initialization. Should be called before this
		/// class or any Mono.Addins class is used. The ordering is very delicate.
		/// </summary>
		public static void Initialize ()
		{
			// we need to save these before initializing mono.addins or else ones that have been update in the
			// plugins directory will be lost.
			IEnumerable<string> savedPlugins = PluginsEnabledBeforeLoad ();
			
			// Initialize Mono.Addins.
			AddinManager.Initialize (Paths.UserPluginsDirectory);	
			
			// reload any enabled plugins that got disabled on init
			if (CorePreferences.PeekDebug)
				AddinManager.Registry.Rebuild (null);
			else
				AddinManager.Registry.Update (null);
			EnableDisabledPlugins (savedPlugins);
			
			// Initialize services before addins that may use them are loaded.
			Services.Initialize ();
			InterfaceManager.Initialize ();
			
			// Now allow loading of non-services.
			foreach (string path in ExtensionPaths)
				AddinManager.AddExtensionNodeHandler (path, OnPluginChanged);
		}
		
		/// <summary>
		/// Refresh the addin registry in case any new plugins have shown up
		/// and also make upgrades.
		/// </summary>
		public static void RefreshPlugins ()
		{
			IEnumerable<string> savedPlugins = PluginsEnabledBeforeLoad ();
			RefreshPlugins (savedPlugins);
		}
		
		/// <summary>
		/// This is a workaround for a Mono.Addins bug where updated addins will get
		/// disabled on update. We save the currently enabled addins, update, then
		/// reenable them with the Id of the new version. It's a bit hackish but lluis
		/// said it's a reasonable approach until that bug is fixed 
	 	/// https://bugzilla.novell.com/show_bug.cgi?id=490302
		/// </summary>
		static void RefreshPlugins (IEnumerable<string> savedPlugins)
		{
			AddinManager.Registry.Update (null);
			EnableDisabledPlugins (savedPlugins);
		}
		
		public static void InstallLocalPlugins ()
		{	
			IEnumerable<string> saved, manual;
			
			manual = Directory.GetFiles (Paths.UserAddinInstallationDirectory, "*.dll")
				.Select (s => Path.GetFileName (s))
				.ForEach (dll => Log.Debug ("Installing {0}", dll));
			
			AddinManager.Registry.Rebuild (null);
			saved = AddinManager.Registry.GetAddins ()
				.Where (addin => manual.Contains (Path.GetFileName (addin.AddinFile)))
				.Select (addin => addin.Id);
				
			EnableDisabledPlugins (saved);
			manual.ForEach (dll => File.Delete (dll));
		}
		
		public static void Enable (Addin addin)
		{
			SetAddinEnabled (addin, true);
		}
		
		public static void Enable (string id)
		{
			Enable (AddinManager.Registry.GetAddin (id));
		}
		
		public static void Disable (Addin addin)
		{
			SetAddinEnabled (addin, false);
		}
		
		public static void Disable (string id)
		{
			Disable (AddinManager.Registry.GetAddin (id));
		}
		
		static void SetAddinEnabled (Addin addin, bool enabled)
		{
			if (addin != null)
				addin.Enabled = enabled;
		}
		
		public static IEnumerable<Addin> GetAddins ()
		{
			return AddinManager.Registry.GetAddins ();
		}
		
		public static bool PluginClassifiesAs (AddinRepositoryEntry entry, string className)
		{
			AddinClassifier classifier = Classifiers.FirstOrDefault (c => c.Name == className);
			return classifier == null ? false : classifier.IsMatch (entry);
		}

		public static bool PluginClassifiesAs (Addin addin, string className)
		{
			AddinClassifier classifier = Classifiers.FirstOrDefault (c => c.Name == className);
			return classifier == null ? false : classifier.IsMatch (addin);
		}

		/// <summary>
		/// Given an addin ID, returns an icon that may represent that addin.
		/// </summary>
		/// <param name="id">
		/// A <see cref="System.String"/> containing an addin ID.
		/// </param>
		/// <returns>
		/// A <see cref="System.String"/> containing an icon name. Can be loaded
		/// via <see cref="Icons"/>.
		/// </returns>
		public static string IconForAddin (string id)
		{   
			string icon;

			// First look for an icon among ItemSources:
			icon = ObjectsForAddin<ItemSource> (id)
				.Select (source => source.Safe.Icon)
				.FirstOrDefault ();
			if (icon != null) return icon;

			// If no icon found among ItemSources, look for an icon among
			// Actions:		
			icon = ObjectsForAddin<Act> (id)
				.Select (source => source.Safe.Icon)
				.FirstOrDefault ();
			if (icon != null) return icon;

			return DefaultPluginIcon;
		}

		/// <value>
		/// All loaded ItemSources.
		/// </value>
		public static IEnumerable<ItemSource> ItemSources {
			get { return AddinManager.GetExtensionObjects ("/Do/ItemSource").OfType<ItemSource> (); }
		}

		/// <value>
		/// All loaded Actions.
		/// </value>
		public static IEnumerable<Act> Actions {
			get { return AddinManager.GetExtensionObjects ("/Do/Action").OfType<Act> (); }
		}
		
		/// <summary>
		/// Returns a list of the plugins that were enabled before Mono.Addins was initialised.
		/// this is read from config.xml.
		/// </summary>
		/// <returns>
		/// A <see cref="IEnumerable"/> of strings containing the versionless plugin id of all
		/// enabled plugins.
		/// </returns>
		static IEnumerable<string> PluginsEnabledBeforeLoad ()
		{
			XmlTextReader reader;
			List<string> plugins;
			
			if (!Directory.Exists (Paths.UserAddinInstallationDirectory))
				return Enumerable.Empty<string> ();
				
			plugins = new List<string> ();
		
			try {
				// set up the reader by loading file, telling it that whitespace doesn't matter, and the DTD is irrelevant
				using (reader = new XmlTextReader (Paths.UserPluginsDirectory.Combine ("addin-db-001", "config.xml"))) {
					reader.XmlResolver = null;
					reader.WhitespaceHandling = WhitespaceHandling.None;
					reader.MoveToContent ();
					
					if (string.IsNullOrEmpty (reader.Name))
						return Enumerable.Empty<string> ();
					
					while (reader.Read ()) {
						string id;
						if (reader.NodeType != XmlNodeType.Element || !reader.HasAttributes)
							continue;
						
						reader.MoveToAttribute ("id");
						id = AddinIdWithoutVersion (reader.Value);
						
						if (string.IsNullOrEmpty (id))
							continue;
							
						reader.MoveToAttribute ("enabled");
						
						if (Boolean.Parse (reader.Value))
							plugins.Add (id);
					}
				}
			} catch (FileNotFoundException e) {
				Log.Debug ("Could not find locate Mono.Addins config.xml: {0}", e.Message);
			} catch (XmlException e) {
				Log.Error ("Error while parsing Mono.Addins config.xml: {0}", e.Message);
				Log.Debug (e.StackTrace);
			}
			
			return plugins;	
		}
		
		static void EnableDisabledPlugins (IEnumerable<string> savedPlugins)
		{
			AddinManager.Registry.GetAddins ()
				.Where (addin => !addin.Enabled && savedPlugins.Any (name => addin.Id.StartsWith (name)))
				.ForEach (addin => Enable (addin));
		}

		static void OnPluginChanged (object sender, ExtensionNodeEventArgs args)
		{
			TypeExtensionNode node = args.ExtensionNode as TypeExtensionNode;
			
			switch (args.Change) {
			case ExtensionChange.Add:
				try {
					object plugin = node.GetInstance ();
					Log<PluginManager>.Debug ("Loaded \"{0}\" from plugin.", plugin.GetType ().Name);
				} catch (Exception e) {
					Log<PluginManager>.Error ("Encountered error loading plugin: {0} \"{1}\"",
							e.GetType ().Name, e.Message);
					Log<PluginManager>.Debug (e.StackTrace);
				}
				break;
			case ExtensionChange.Remove:
				try {
					object plugin = node.GetInstance ();
					Log<PluginManager>.Debug ("Unloaded \"{0}\".", plugin.GetType ().Name);
				} catch (Exception e) {
					Log<PluginManager>.Error ("Encountered error unloading plugin: {0} \"{1}\"",
							e.GetType ().Name, e.Message);
					Log<PluginManager>.Debug (e.StackTrace);
				}
				break;
			}	
		}
		
		/// <summary>
		/// Get all objects conforming to type T provided by a given addin.
		/// </summary>
		/// <param name="id">
		/// A <see cref="System.String"/> containing an addin id.
		/// </param>
		/// <returns>
		/// A <see cref="IEnumerable`1"/> of instances of type T.
		/// </returns>
		static IEnumerable<T> ObjectsForAddin<T> (string id) where T : class
		{
			// TODO try using AddinManager.GetExtensionPoints (Type)
			foreach (string path in ExtensionPaths) {
				foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes (path)) {
					object instance;

					try {
						instance = node.GetInstance ();
					} catch (Exception e) {
						Log<PluginManager>.Error ("ObjectsForAddin encountered an error: {0} \"{1}\"",
								e.GetType ().Name, e.Message);
						Log<PluginManager>.Debug (e.StackTrace);
						continue;
					}

					if (!(instance is T))
						continue; // Does not conform to required type.
					if (Addin.GetIdName (id) != Addin.GetIdName (node.Addin.Id))
						continue; // Instances not from same addin. Version mismatch?
					yield return instance as T;
				}
			}
		}

		/// <summary>
		/// Get all IConfigurable instances loaded from plugins.
		/// </summary>
		/// <param name="id">
		/// A <see cref="System.String"/> containing an addin id.
		/// </param>
		/// <returns>
		/// A <see cref="IEnumerable`1"/> of <see cref="IConfigurable"/>
		/// provided by the addin for that id.
		/// </returns>
		public static IEnumerable<IConfigurable> ConfigurablesForAddin (string id)
		{
			return ObjectsForAddin<IConfigurable> (id);
		}
		
		static string AddinIdWithoutVersion (string id)
		{
			return id.Substring (0, id.IndexOf (','));
		}
	}
}