Pretty-print.
[beagle.git] / Util / Conf.cs
blobce6415973adfe96950e52910ea830d2bf3cd4c55
1 //
2 // Conf.cs
3 //
4 // Copyright (C) 2005 Novell, Inc.
5 //
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a copy
9 // of this software and associated documentation files (the "Software"), to deal
10 // in the Software without restriction, including without limitation the rights
11 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 // copies of the Software, and to permit persons to whom the Software is
13 // furnished to do so, subject to the following conditions:
15 // The above copyright notice and this permission notice shall be included in all
16 // copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 // SOFTWARE.
27 using System;
28 using System.Collections;
29 using System.IO;
30 using System.Diagnostics;
31 using System.Reflection;
32 using System.Xml.Serialization;
33 using System.Text.RegularExpressions;
35 using Beagle.Util;
37 namespace Beagle.Util {
39 public class Conf {
41 // No instantiation
42 private Conf () { }
44 public static Hashtable Sections;
46 public static IndexingConfig Indexing = null;
47 public static DaemonConfig Daemon = null;
48 public static SearchingConfig Searching = null;
50 private static string configs_dir;
51 private static Hashtable mtimes;
52 private static Hashtable subscriptions;
54 private static bool watching_for_updates;
55 private static bool update_watch_present;
57 private static BindingFlags method_search_flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod;
59 public delegate void ConfigUpdateHandler (Section section);
61 static Conf ()
63 Sections = new Hashtable (3);
64 mtimes = new Hashtable (3);
65 subscriptions = new Hashtable (3);
67 configs_dir = Path.Combine (PathFinder.StorageDir, "config");
68 if (!Directory.Exists (configs_dir))
69 Directory.CreateDirectory (configs_dir);
71 Conf.Load ();
74 public static void WatchForUpdates ()
76 // Make sure we don't try and watch for updates more than once
77 if (update_watch_present)
78 return;
80 if (Inotify.Enabled) {
81 Inotify.Subscribe (configs_dir, OnInotifyEvent, Inotify.EventType.Create | Inotify.EventType.CloseWrite);
82 } else {
83 // Poll for updates every 60 secs
84 GLib.Timeout.Add (60000, new GLib.TimeoutHandler (CheckForUpdates));
87 update_watch_present = true;
90 private static void OnInotifyEvent (Inotify.Watch watch, string path, string subitem, string srcpath, Inotify.EventType type)
92 if (subitem == "" || watching_for_updates == false)
93 return;
95 Load ();
98 private static bool CheckForUpdates ()
100 if (watching_for_updates)
101 Load ();
102 return true;
105 public static void Subscribe (Type type, ConfigUpdateHandler callback)
107 if (!subscriptions.ContainsKey (type))
108 subscriptions.Add (type, new ArrayList (1));
110 ArrayList callbacks = (ArrayList) subscriptions [type];
111 callbacks.Add (callback);
114 private static void NotifySubscribers (Section section)
116 Type type = section.GetType ();
117 ArrayList callbacks = (ArrayList) subscriptions [type];
119 if (callbacks == null)
120 return;
122 foreach (ConfigUpdateHandler callback in callbacks)
123 callback (section);
126 public static void Load ()
128 Load (false);
131 public static void Load (bool force)
133 Section temp;
135 // FIXME: Yeah
136 LoadFile (typeof (IndexingConfig), Indexing, out temp, force);
137 Indexing = (IndexingConfig) temp;
138 NotifySubscribers (Indexing);
140 LoadFile (typeof (DaemonConfig), Daemon, out temp, force);
141 Daemon = (DaemonConfig) temp;
142 NotifySubscribers (Daemon);
144 LoadFile (typeof (SearchingConfig), Searching, out temp, force);
145 Searching = (SearchingConfig) temp;
146 NotifySubscribers (Searching);
148 watching_for_updates = true;
151 public static void Save ()
153 Save (false);
156 public static void Save (bool force)
158 foreach (Section section in Sections.Values)
159 if (force || section.SaveNeeded)
160 SaveFile (section);
163 private static bool LoadFile (Type type, Section current, out Section section, bool force)
165 section = current;
166 object [] attrs = Attribute.GetCustomAttributes (type, typeof (ConfigSection));
167 if (attrs.Length == 0)
168 throw new ConfigException ("Could not find ConfigSection attribute on " + type);
170 string sectionname = ((ConfigSection) attrs [0]).Name;
171 string filename = sectionname + ".xml";
172 string filepath = Path.Combine (configs_dir, filename);
173 if (!File.Exists (filepath)) {
174 if (current == null)
175 ConstructDefaultSection (type, sectionname, out section);
176 return false;
179 if (!force && current != null && mtimes.ContainsKey (sectionname) &&
180 File.GetLastWriteTimeUtc (filepath).CompareTo ((DateTime) mtimes [sectionname]) <= 0)
181 return false;
183 Logger.Log.Debug ("Loading {0} from {1}", type, filename);
184 FileStream fs = null;
186 try {
187 fs = File.Open (filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
188 XmlSerializer serializer = new XmlSerializer (type);
189 section = (Section) serializer.Deserialize (fs);
190 } catch (Exception e) {
191 Logger.Log.Error (e, "Could not load configuration from {0}:", filename);
192 if (fs != null)
193 fs.Close ();
194 if (current == null)
195 ConstructDefaultSection (type, sectionname, out section);
196 return false;
199 fs.Close ();
200 Sections.Remove (sectionname);
201 Sections.Add (sectionname, section);
202 mtimes.Remove (sectionname);
203 mtimes.Add (sectionname, File.GetLastWriteTimeUtc (filepath));
204 return true;
207 private static bool SaveFile (Section section)
209 Type type = section.GetType ();
210 object [] attrs = Attribute.GetCustomAttributes (type, typeof (ConfigSection));
211 if (attrs.Length == 0)
212 throw new ConfigException ("Could not find ConfigSection attribute on " + type);
214 string sectionname = ((ConfigSection) attrs [0]).Name;
215 string filename = sectionname + ".xml";
216 string filepath = Path.Combine (configs_dir, filename);
218 Logger.Log.Debug ("Saving {0} to {1}", type, filename);
219 FileStream fs = null;
221 try {
222 watching_for_updates = false;
223 fs = new FileStream (filepath, FileMode.Create);
224 XmlSerializer serializer = new XmlSerializer (type);
225 XmlFu.SerializeUtf8 (serializer, fs, section);
226 } catch (Exception e) {
227 if (fs != null)
228 fs.Close ();
229 Logger.Log.Error ("Could not save configuration to {0}: {1}", filename, e);
230 watching_for_updates = true;
231 return false;
234 fs.Close ();
235 mtimes.Remove (sectionname);
236 mtimes.Add (sectionname, File.GetLastWriteTimeUtc (filepath));
237 watching_for_updates = true;
238 return true;
241 private static void ConstructDefaultSection (Type type, string sectionname, out Section section)
243 ConstructorInfo ctor = type.GetConstructor (Type.EmptyTypes);
244 section = (Section) ctor.Invoke (null);
245 Sections.Remove (sectionname);
246 Sections.Add (sectionname, section);
249 // Lists all config file options in a hash table where key is option name,
250 // and value is description.
251 public static Hashtable GetOptions (Section section)
253 Hashtable options = new Hashtable ();
254 MemberInfo [] members = section.GetType ().GetMembers (method_search_flags);
256 // Find all of the methods ("options") inside the specified section
257 // object which have the ConfigOption attribute.
258 foreach (MemberInfo member in members) {
259 object [] attrs = member.GetCustomAttributes (typeof (ConfigOption), false);
260 if (attrs.Length > 0)
261 options.Add (member.Name, ((ConfigOption) attrs [0]).Description);
264 return options;
267 public static bool InvokeOption (Section section, string option, string [] args, out string output)
269 MethodInfo method = section.GetType ().GetMethod (option, method_search_flags);
270 if (method == null) {
271 string msg = String.Format ("No such method '{0}' for section '{1}'", option, section);
272 throw new ConfigException(msg);
274 object [] attrs = method.GetCustomAttributes (typeof (ConfigOption), false);
275 if (attrs.Length == 0) {
276 string msg = String.Format ("Method '{0}' is not a configurable option", option);
277 throw new ConfigException (msg);
280 // Check the required number of parameters have been provided
281 ConfigOption attr = (ConfigOption) attrs [0];
282 if (attr.Params > 0 && args.Length < attr.Params) {
283 string msg = String.Format ("Option '{0}' requires {1} parameter(s): {2}", option, attr.Params, attr.ParamsDescription);
284 throw new ConfigException (msg);
287 object [] methodparams = { null, args };
288 bool result = (bool) method.Invoke (section, methodparams);
289 output = (string) methodparams [0];
291 // Mark the section as save-needed if we just changed something
292 if (result && attr.IsMutator)
293 section.SaveNeeded = true;
295 return result;
298 [ConfigSection (Name="searching")]
299 public class SearchingConfig : Section {
301 private KeyBinding show_search_window_binding = new KeyBinding ("F12");
302 public KeyBinding ShowSearchWindowBinding {
303 get { return show_search_window_binding; }
304 set { show_search_window_binding = value; }
307 // BeagleSearch window position and dimension
308 // stored as percentage of screen co-ordinates
309 // to deal with change of resolution problem - hints from tberman
311 private float beagle_search_pos_x = 0;
312 public float BeaglePosX {
313 get { return beagle_search_pos_x; }
314 set { beagle_search_pos_x = value; }
317 private float beagle_search_pos_y = 0;
318 public float BeaglePosY {
319 get { return beagle_search_pos_y; }
320 set { beagle_search_pos_y = value; }
323 private float beagle_search_width = 0;
324 public float BeagleSearchWidth {
325 get { return beagle_search_width; }
326 set { beagle_search_width = value; }
329 private float beagle_search_height = 0;
330 public float BeagleSearchHeight {
331 get { return beagle_search_height; }
332 set { beagle_search_height = value; }
335 // ah!We want a Queue but Queue doesnt serialize *easily*
336 private ArrayList search_history = new ArrayList ();
337 public ArrayList SearchHistory {
338 get { return search_history; }
339 set { search_history = value; }
342 private bool beagle_search_auto_search = true;
343 public bool BeagleSearchAutoSearch {
344 get { return beagle_search_auto_search; }
345 set { beagle_search_auto_search = value; }
350 [ConfigSection (Name="daemon")]
351 public class DaemonConfig : Section {
352 private ArrayList static_queryables = new ArrayList ();
353 public ArrayList StaticQueryables {
354 get { return static_queryables; }
355 set { static_queryables = value; }
358 // By default, every backend is allowed.
359 // Only maintain a list of denied backends.
360 private ArrayList denied_backends = new ArrayList ();
361 public ArrayList DeniedBackends {
362 get { return denied_backends; }
363 set { denied_backends = value; }
366 private bool allow_static_backend = false; // by default, false
367 public bool AllowStaticBackend {
368 get { return allow_static_backend; }
369 // Don't really want to expose this, but serialization requires it
370 set { allow_static_backend = value; }
373 private bool index_synchronization = true;
374 public bool IndexSynchronization {
375 get { return index_synchronization; }
376 // Don't really want to expose this, but serialization requires it
377 set { index_synchronization = value; }
380 [ConfigOption (Description="Enable a backend", Params=1, ParamsDescription="Name of the backend to enable")]
381 internal bool AllowBackend (out string output, string [] args)
383 denied_backends.Remove (args [0]);
384 output = "Backend allowed (need to restart beagled for changes to take effect).";
385 return true;
388 [ConfigOption (Description="Disable a backend", Params=1, ParamsDescription="Name of the backend to disable")]
389 internal bool DenyBackend (out string output, string [] args)
391 denied_backends.Add (args [0]);
392 output = "Backend disabled (need to restart beagled for changes to take effect).";
393 return true;
396 private bool allow_root = false;
397 public bool AllowRoot {
398 get { return allow_root; }
399 set { allow_root = value; }
402 [ConfigOption (Description="Add a static queryable", Params=1, ParamsDescription="Index path")]
403 internal bool AddStaticQueryable (out string output, string [] args)
405 static_queryables.Add (args [0]);
406 output = "Static queryable added.";
407 return true;
410 [ConfigOption (Description="Remove a static queryable", Params=1, ParamsDescription="Index path")]
411 internal bool DelStaticQueryable (out string output, string [] args)
413 static_queryables.Remove (args [0]);
414 output = "Static queryable removed.";
415 return true;
418 [ConfigOption (Description="List user-specified static queryables", IsMutator=false)]
419 internal bool ListStaticQueryables (out string output, string [] args)
421 output = "User-specified static queryables:\n";
422 foreach (string index_path in static_queryables)
423 output += String.Format (" - {0}\n", index_path);
424 return true;
427 [ConfigOption (Description="Toggles whether static indexes will be enabled")]
428 internal bool ToggleAllowStaticBackend (out string output, string [] args)
430 allow_static_backend = !allow_static_backend;
431 output = "Static indexes are " + ((allow_static_backend) ? "enabled" : "disabled") + " (need to restart beagled for changes to take effect).";
432 return true;
435 [ConfigOption (Description="Toggles whether your indexes will be synchronized locally if your home directory is on a network device (eg. NFS/Samba)")]
436 internal bool ToggleIndexSynchronization (out string output, string [] args)
438 index_synchronization = !index_synchronization;
439 output = "Index Synchronization is " + ((index_synchronization) ? "enabled" : "disabled") + ".";
440 return true;
443 [ConfigOption (Description="Toggles whether Beagle can be run as root")]
444 internal bool ToggleAllowRoot (out string output, string [] args)
446 allow_root = ! allow_root;
447 if (allow_root)
448 output = "Beagle is now permitted to run as root";
449 else
450 output = "Beagle is no longer permitted to run as root";
451 return true;
455 [ConfigSection (Name="indexing")]
456 public class IndexingConfig : Section
458 private ArrayList roots = new ArrayList ();
459 [XmlArray]
460 [XmlArrayItem(ElementName="Root", Type=typeof(string))]
461 public ArrayList Roots {
462 get { return roots; }
463 set { roots = value; }
466 private bool index_home_dir = true;
467 public bool IndexHomeDir {
468 get { return index_home_dir; }
469 set { index_home_dir = value; }
472 private bool index_on_battery = true;
473 public bool IndexOnBattery {
474 get { return index_on_battery; }
475 set { index_on_battery = value; }
478 private ArrayList excludes = new ArrayList ();
479 [XmlArray]
480 [XmlArrayItem (ElementName="ExcludeItem", Type=typeof(ExcludeItem))]
481 public ArrayList Excludes {
482 get { return excludes; }
483 set { excludes = value; }
486 [ConfigOption (Description="List the indexing roots", IsMutator=false)]
487 internal bool ListRoots (out string output, string [] args)
489 output = "Current roots:\n";
490 if (this.index_home_dir == true)
491 output += " - Your home directory\n";
492 foreach (string root in roots)
493 output += " - " + root + "\n";
495 return true;
498 [ConfigOption (Description="Toggles whether your home directory is to be indexed as a root")]
499 internal bool IndexHome (out string output, string [] args)
501 if (index_home_dir)
502 output = "Your home directory will not be indexed.";
503 else
504 output = "Your home directory will be indexed.";
505 index_home_dir = !index_home_dir;
506 return true;
509 [ConfigOption (Description="Toggles whether any data should be indexed if the system is on battery")]
510 internal bool IndexWhileOnBattery (out string output, string [] args)
512 if (index_on_battery)
513 output = "Data will not be indexed while on battery.";
514 else
515 output = "Data will be indexed while on battery.";
516 index_on_battery = !index_on_battery;
517 return true;
520 [ConfigOption (Description="Add a root path to be indexed", Params=1, ParamsDescription="A path")]
521 internal bool AddRoot (out string output, string [] args)
523 roots.Add (args [0]);
524 output = "Root added.";
525 return true;
528 [ConfigOption (Description="Remove an indexing root", Params=1, ParamsDescription="A path")]
529 internal bool DelRoot (out string output, string [] args)
531 roots.Remove (args [0]);
532 output = "Root removed.";
533 return true;
536 [ConfigOption (Description="List user-specified resources to be excluded from indexing", IsMutator=false)]
537 internal bool ListExcludes (out string output, string [] args)
539 output = "User-specified resources to be excluded from indexing:\n";
540 foreach (ExcludeItem exclude_item in excludes)
541 output += String.Format (" - [{0}] {1}\n", exclude_item.Type.ToString (), exclude_item.Value);
542 return true;
545 [ConfigOption (Description="Add a resource to exclude from indexing", Params=2, ParamsDescription="A type [path/pattern/mailfolder], a path/pattern/name")]
546 internal bool AddExclude (out string output, string [] args)
548 ExcludeType type;
549 try {
550 type = (ExcludeType) Enum.Parse (typeof (ExcludeType), args [0], true);
551 } catch {
552 output = String.Format("Invalid type '{0}'. Valid types: Path, Pattern, MailFolder", args [0]);
553 return false;
556 excludes.Add (new ExcludeItem (type, args [1]));
557 output = "Exclude added.";
558 return true;
561 [ConfigOption (Description="Remove an excluded resource", Params=2, ParamsDescription="A type [path/pattern/mailfolder], a path/pattern/name")]
562 internal bool DelExclude (out string output, string [] args)
564 ExcludeType type;
565 try {
566 type = (ExcludeType) Enum.Parse (typeof (ExcludeType), args [0], true);
567 } catch {
568 output = String.Format("Invalid type '{0}'. Valid types: Path, Pattern, MailFolder", args [0]);
569 return false;
572 foreach (ExcludeItem item in excludes) {
573 if (item.Type != type || item.Value != args [1])
574 continue;
575 excludes.Remove (item);
576 output = "Exclude removed.";
577 return true;
580 output = "Could not find requested exclude to remove.";
581 return false;
586 public class Section {
587 [XmlIgnore]
588 public bool SaveNeeded = false;
591 private class ConfigOption : Attribute {
592 public string Description;
593 public int Params;
594 public string ParamsDescription;
595 public bool IsMutator = true;
598 private class ConfigSection : Attribute {
599 public string Name;
602 public class ConfigException : Exception {
603 public ConfigException (string msg) : base (msg) { }
608 //////////////////////////////////////////////////////////////////////
610 public enum ExcludeType {
611 Path,
612 Pattern,
613 MailFolder
616 public class ExcludeItem {
618 private ExcludeType type;
619 private string val;
621 [XmlAttribute]
622 public ExcludeType Type {
623 get { return type; }
624 set { type = value; }
627 private string exactMatch;
628 private string prefix;
629 private string suffix;
630 private Regex regex;
632 [XmlAttribute]
633 public string Value {
634 get { return val; }
635 set {
636 switch (type) {
637 case ExcludeType.Path:
638 case ExcludeType.MailFolder:
639 prefix = value;
640 break;
642 case ExcludeType.Pattern:
643 if (value.StartsWith ("/") && value.EndsWith ("/")) {
644 regex = new Regex (value.Substring (1, value.Length - 2));
645 break;
648 int i = value.IndexOf ('*');
649 if (i == -1) {
650 exactMatch = value;
651 } else {
652 if (i > 0)
653 prefix = value.Substring (0, i);
654 if (i < value.Length-1)
655 suffix = value.Substring (i+1);
657 break;
660 val = value;
664 public ExcludeItem () {}
666 public ExcludeItem (ExcludeType type, string value) {
667 this.Type = type;
668 this.Value = value;
671 public bool IsMatch (string param)
673 switch (Type) {
674 case ExcludeType.Path:
675 case ExcludeType.MailFolder:
676 if (prefix != null && ! param.StartsWith (prefix))
677 return false;
679 return true;
681 case ExcludeType.Pattern:
682 if (exactMatch != null)
683 return param == exactMatch;
684 if (prefix != null && ! param.StartsWith (prefix))
685 return false;
686 if (suffix != null && ! param.EndsWith (suffix))
687 return false;
688 if (regex != null && ! regex.IsMatch (param))
689 return false;
691 return true;
694 return false;
697 public override bool Equals (object obj)
699 ExcludeItem exclude = obj as ExcludeItem;
700 return (exclude != null && exclude.Type == type && exclude.Value == val);
703 public override int GetHashCode ()
705 return (this.Value.GetHashCode () ^ (int) this.Type);
710 //////////////////////////////////////////////////////////////////////
712 public class KeyBinding {
713 public string Key;
715 [XmlAttribute]
716 public bool Ctrl = false;
717 [XmlAttribute]
718 public bool Alt = false;
720 public KeyBinding () {}
721 public KeyBinding (string key) : this (key, false, false) {}
723 public KeyBinding (string key, bool ctrl, bool alt)
725 Key = key;
726 Ctrl = ctrl;
727 Alt = alt;
730 public override string ToString ()
732 string result = "";
734 if (Ctrl)
735 result += "<Ctrl>";
736 if (Alt)
737 result += "<Alt>";
739 result += Key;
741 return result;
744 public string ToReadableString ()
746 return ToString ().Replace (">", "-").Replace ("<", "");