cvsimport
[beagle.git] / search / Tiles / TileActivator.cs
blobebf43ebfe6c9d12522da351fb0caa133e95e3c50
1 using System;
2 using System.Collections;
3 using System.Reflection;
4 using Mono.Posix;
6 using Beagle.Util;
8 namespace Search.Tiles {
10 // FIXME: Should we call this something else?
11 public abstract class TileActivator : IComparable {
13 private ArrayList flavors;
15 protected TileActivator ()
17 this.flavors = new ArrayList ();
20 public abstract Tile BuildTile (Beagle.Hit hit, Beagle.Query query);
22 public int Weight = 0;
24 protected void AddSupportedFlavor (HitFlavor flavor)
26 flavors.Add (flavor);
29 public virtual bool Validate (Beagle.Hit hit)
31 if (flavors.Count < 1)
32 return false;
34 Weight = 0;
36 HitFlavor best = null;
38 foreach (HitFlavor flavor in flavors) {
39 if (! flavor.IsMatch (hit))
40 continue;
42 if (best == null) {
43 best = flavor;
44 continue;
47 if (flavor.Weight > best.Weight) {
48 best = flavor;
52 if (best != null) {
53 Weight += best.Weight;
54 return true;
57 return false;
60 public int CompareTo (object o)
62 TileActivator other = (TileActivator)o;
64 if (other == null)
65 return 1;
67 return (this.Weight - other.Weight);
71 // FIXME: Rename this and move out of this file
72 public static class TileActivatorOrg {
74 private static ArrayList activators;
76 static TileActivatorOrg ()
78 activators = new ArrayList ();
80 foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies ()) {
82 foreach (Type type in ReflectionFu.GetTypesFromAssemblyAttribute (assembly, typeof (TileActivatorTypesAttribute))) {
83 try {
84 activators.Add ((TileActivator) Activator.CreateInstance (type));
85 } catch (Exception e) {
86 Console.WriteLine ("Caught exception while instantiating tile");
87 Console.WriteLine (e);
93 public static Tile MakeTile (Beagle.Hit hit, Beagle.Query query)
95 TileActivator best = null;
97 try {
98 foreach (TileActivator activator in activators) {
99 if (! activator.Validate (hit))
100 continue;
102 if (best == null) {
103 best = activator;
104 continue;
107 if (activator.Weight > best.Weight)
108 best = activator;
111 if (best != null)
112 return best.BuildTile (hit, query);
113 } catch (Exception e) {
114 Console.WriteLine ("Error instantiating tile:\n{0}", e);
117 return null;
121 [AttributeUsage (AttributeTargets.Assembly)]
122 public class TileActivatorTypesAttribute : TypeCacheAttribute {
123 public TileActivatorTypesAttribute (params Type[] types) : base (types) { }