Fix a bunch of memory problems in beagle:
[beagle.git] / search / Tiles / TileActivator.cs
blobf3878ce068d0d7dcec8d19c7c7d84ad673c19f84
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 bool first = true;
84 foreach (Type type in ReflectionFu.GetTypesFromAssemblyAttribute (assembly, typeof (TileActivatorTypesAttribute))) {
85 if (first) {
86 Console.WriteLine ("* Assembly: {0}", assembly.FullName);
87 first = false;
89 Console.WriteLine (" - {0}", type);
91 try {
92 activators.Add ((TileActivator) Activator.CreateInstance (type));
93 } catch (Exception e) {
94 Console.WriteLine ("Caught exception while instantiating tile.");
100 public static Tile MakeTile (Beagle.Hit hit, Beagle.Query query)
102 TileActivator best = null;
104 try {
105 foreach (TileActivator activator in activators) {
106 if (! activator.Validate (hit))
107 continue;
109 if (best == null) {
110 best = activator;
111 continue;
114 if (activator.Weight > best.Weight)
115 best = activator;
118 if (best != null)
119 return best.BuildTile (hit, query);
120 } catch (Exception e) {
121 Console.WriteLine ("Error instantiating tile:\n{0}", e);
124 return null;
128 [AttributeUsage (AttributeTargets.Assembly)]
129 public class TileActivatorTypesAttribute : TypeCacheAttribute {
130 public TileActivatorTypesAttribute (params Type[] types) : base (types) { }