4 // Copyright (C) 2005 Novell, Inc.
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
28 using System
.Collections
;
30 using System
.Diagnostics
;
31 using System
.Reflection
;
32 using System
.Xml
.Serialization
;
33 using System
.Text
.RegularExpressions
;
37 namespace Beagle
.Util
{
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
);
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
);
74 public static void WatchForUpdates ()
76 // Make sure we don't try and watch for updates more than once
77 if (update_watch_present
)
80 if (Inotify
.Enabled
) {
81 Inotify
.Subscribe (configs_dir
, OnInotifyEvent
, Inotify
.EventType
.Create
| Inotify
.EventType
.CloseWrite
);
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)
98 private static bool CheckForUpdates ()
100 if (watching_for_updates
)
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)
122 foreach (ConfigUpdateHandler callback
in callbacks
)
126 public static void Load ()
131 public static void Load (bool force
)
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 ()
156 public static void Save (bool force
)
158 foreach (Section section
in Sections
.Values
)
159 if (force
|| section
.SaveNeeded
)
163 private static bool LoadFile (Type type
, Section current
, out Section section
, bool force
)
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
)) {
175 ConstructDefaultSection (type
, sectionname
, out section
);
179 if (!force
&& current
!= null && mtimes
.ContainsKey (sectionname
) &&
180 File
.GetLastWriteTimeUtc (filepath
).CompareTo ((DateTime
) mtimes
[sectionname
]) <= 0)
183 Logger
.Log
.Debug ("Loading {0} from {1}", type
, filename
);
184 FileStream fs
= null;
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
);
195 ConstructDefaultSection (type
, sectionname
, out section
);
200 Sections
.Remove (sectionname
);
201 Sections
.Add (sectionname
, section
);
202 mtimes
.Remove (sectionname
);
203 mtimes
.Add (sectionname
, File
.GetLastWriteTimeUtc (filepath
));
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;
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
) {
229 Logger
.Log
.Error ("Could not save configuration to {0}: {1}", filename
, e
);
230 watching_for_updates
= true;
235 mtimes
.Remove (sectionname
);
236 mtimes
.Add (sectionname
, File
.GetLastWriteTimeUtc (filepath
));
237 watching_for_updates
= 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
);
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;
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).";
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).";
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.";
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.";
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
);
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).";
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") + ".";
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
;
448 output
= "Beagle is now permitted to run as root";
450 output
= "Beagle is no longer permitted to run as root";
455 [ConfigSection (Name
="indexing")]
456 public class IndexingConfig
: Section
458 private ArrayList roots
= new ArrayList ();
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 ();
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";
498 [ConfigOption (Description
="Toggles whether your home directory is to be indexed as a root")]
499 internal bool IndexHome (out string output
, string [] args
)
502 output
= "Your home directory will not be indexed.";
504 output
= "Your home directory will be indexed.";
505 index_home_dir
= !index_home_dir
;
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.";
515 output
= "Data will be indexed while on battery.";
516 index_on_battery
= !index_on_battery
;
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.";
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.";
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
);
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
)
550 type
= (ExcludeType
) Enum
.Parse (typeof (ExcludeType
), args
[0], true);
552 output
= String
.Format("Invalid type '{0}'. Valid types: Path, Pattern, MailFolder", args
[0]);
556 excludes
.Add (new ExcludeItem (type
, args
[1]));
557 output
= "Exclude added.";
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
)
566 type
= (ExcludeType
) Enum
.Parse (typeof (ExcludeType
), args
[0], true);
568 output
= String
.Format("Invalid type '{0}'. Valid types: Path, Pattern, MailFolder", args
[0]);
572 foreach (ExcludeItem item
in excludes
) {
573 if (item
.Type
!= type
|| item
.Value
!= args
[1])
575 excludes
.Remove (item
);
576 output
= "Exclude removed.";
580 output
= "Could not find requested exclude to remove.";
586 public class Section
{
588 public bool SaveNeeded
= false;
591 private class ConfigOption
: Attribute
{
592 public string Description
;
594 public string ParamsDescription
;
595 public bool IsMutator
= true;
598 private class ConfigSection
: Attribute
{
602 public class ConfigException
: Exception
{
603 public ConfigException (string msg
) : base (msg
) { }
608 //////////////////////////////////////////////////////////////////////
610 public enum ExcludeType
{
616 public class ExcludeItem
{
618 private ExcludeType type
;
622 public ExcludeType Type
{
624 set { type = value; }
627 private string exactMatch
;
628 private string prefix
;
629 private string suffix
;
633 public string Value
{
637 case ExcludeType
.Path
:
638 case ExcludeType
.MailFolder
:
642 case ExcludeType
.Pattern
:
643 if (value.StartsWith ("/") && value.EndsWith ("/")) {
644 regex
= new Regex (value.Substring (1, value.Length
- 2));
648 int i
= value.IndexOf ('*');
653 prefix
= value.Substring (0, i
);
654 if (i
< value.Length
-1)
655 suffix
= value.Substring (i
+1);
664 public ExcludeItem () {}
666 public ExcludeItem (ExcludeType type
, string value) {
671 public bool IsMatch (string param
)
674 case ExcludeType
.Path
:
675 case ExcludeType
.MailFolder
:
676 if (prefix
!= null && ! param
.StartsWith (prefix
))
681 case ExcludeType
.Pattern
:
682 if (exactMatch
!= null)
683 return param
== exactMatch
;
684 if (prefix
!= null && ! param
.StartsWith (prefix
))
686 if (suffix
!= null && ! param
.EndsWith (suffix
))
688 if (regex
!= null && ! regex
.IsMatch (param
))
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
{
716 public bool Ctrl
= false;
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
)
730 public override string ToString ()
744 public string ToReadableString ()
746 return ToString ().Replace (">", "-").Replace ("<", "");