]> gitweb @ CieloNegro.org - task-reporter.git/blob - src/main/scala/preferences.scala
wip
[task-reporter.git] / src / main / scala / preferences.scala
1 // Borrowed from http://code.google.com/p/preferscala/
2 package preferscala;
3 import sbinary._;
4 import sbinary.Operations._;
5 import java.io.File;
6 import java.util.prefs.Preferences;
7
8 sealed abstract class PreferenceType{
9   private[preferscala] def nodeForPackage(clazz : Class[_]) : Preferences;
10   private[preferscala] def root : Preferences;
11 }
12
13 object PreferenceType{
14   case object User extends PreferenceType{
15     private[preferscala] def nodeForPackage(clazz : Class[_]) = Preferences.userNodeForPackage(clazz);
16     private[preferscala] def root = Preferences.userRoot;
17   }
18
19   case object System extends PreferenceType{
20     private[preferscala] def nodeForPackage(clazz : Class[_]) = Preferences.systemNodeForPackage(clazz);
21     private[preferscala] def root = Preferences.systemRoot;
22   }
23 }
24
25 abstract class PreferenceGroup{
26   def underlying : Preferences;
27   class Preference[T](name : String, default : => T)(implicit bin : Format[T]){
28     private var localCache : T = null.asInstanceOf[T];
29
30     def apply() : T = {
31       if (localCache == null){
32         var bytes = underlying.getByteArray(name, null);
33         if (bytes == null){
34           localCache = default;
35         } else {
36           localCache = fromByteArray[T](bytes)
37         }
38       }
39       localCache
40     }
41
42     def update(t : T){
43       localCache = t;
44       underlying.putByteArray(name, toByteArray[T](t));
45     }
46
47     def reset(){
48       localCache = null.asInstanceOf[T];
49       underlying.remove(name);
50       underlying.flush();
51     }
52
53     def exportToFile(file : File){
54       toFile(apply())(file);
55     }
56
57     def loadFromFile(file : File){
58       update(fromFile[T](file));
59     }
60   }
61 }
62
63 class NamedGroup(groupName : String, pt : PreferenceType) extends PreferenceGroup{
64   val underlying = pt.root.node(groupName);
65 }
66
67 abstract class PackageGroup(pt : PreferenceType) extends PreferenceGroup{
68   val underlying = pt.nodeForPackage(getClass);
69 }