+ if self.save_disabled or self.locations == []:
+ self.saved_value = None
+ else:
+ self.saved_value = self.tostring([x[0] for x in self.locations])
+
+ def isChanged(self):
+ sv = self.saved_value
+ if val is None and self.locations == []:
+ return False
+ return self.tostring([x[0] for x in self.locations]) != sv
+
+ def mountpointsChanged(self, action, dev):
+ print "Mounts changed: ", action, dev
+ mp = dev.mountpoint+"/"
+ if action == "add":
+ self.addedMount(mp)
+ elif action == "remove":
+ self.removedMount(mp)
+ self.refreshMountpoints()
+
+ def addedMount(self, mp):
+ for x in self.locations:
+ if x[1] == mp:
+ x[2] = True
+ elif x[1] == None and os.path.exists(x[0]):
+ x[1] = self.getMountpoint(x[0])
+ x[2] = True
+
+ def removedMount(self, mp):
+ for x in self.locations:
+ if x[1] == mp:
+ x[2] = False
+
+ def refreshMountpoints(self):
+ self.mountpoints = [p.mountpoint + "/" for p in harddiskmanager.getMountedPartitions() if p.mountpoint != "/"]
+ self.mountpoints.sort(key = lambda x: -len(x))
+
+ def checkChangedMountpoints(self):
+ oldmounts = self.mountpoints
+ self.refreshMountpoints()
+ if oldmounts == self.mountpoints:
+ return
+ for x in oldmounts:
+ if not x in self.mountpoints:
+ self.removedMount(x)
+ for x in self.mountpoints:
+ if not x in oldmounts:
+ self.addedMount(x)
+
+ def getMountpoint(self, file):
+ file = os.path.realpath(file)+"/"
+ for m in self.mountpoints:
+ if file.startswith(m):
+ return m
+ return None
+
+ def handleKey(self, key):
+ if key == KEY_LEFT:
+ self.pos -= 1
+ if self.pos < -1:
+ self.pos = len(self.value)-1
+ elif key == KEY_RIGHT:
+ self.pos += 1
+ if self.pos >= len(self.value):
+ self.pos = -1
+ elif key in [KEY_HOME, KEY_END]:
+ self.pos = -1
+
+ def getText(self):
+ return " ".join(self.value)
+
+ def getMulti(self, selected):
+ if not selected:
+ valstr = " ".join(self.value)
+ if self.visible_width and len(valstr) > self.visible_width:
+ return ("text", valstr[0:self.visible_width])
+ else:
+ return ("text", valstr)
+ else:
+ i = 0
+ valstr = ""
+ ind1 = 0
+ ind2 = 0
+ for val in self.value:
+ if i == self.pos:
+ ind1 = len(valstr)
+ valstr += str(val)+" "
+ if i == self.pos:
+ ind2 = len(valstr)
+ i += 1
+ if self.visible_width and len(valstr) > self.visible_width:
+ if ind1+1 < self.visible_width/2:
+ off = 0
+ else:
+ off = min(ind1+1-self.visible_width/2, len(valstr)-self.visible_width)
+ return ("mtext", valstr[off:off+self.visible_width], range(ind1-off,ind2-off))
+ else:
+ return ("mtext", valstr, range(ind1,ind2))
+
+ def onDeselect(self, session):
+ self.pos = -1
+
+# nothing.
+class ConfigNothing(ConfigSelection):
+ def __init__(self):
+ ConfigSelection.__init__(self, choices = [""])
+
+# until here, 'saved_value' always had to be a *string*.
+# now, in ConfigSubsection, and only there, saved_value
+# is a dict, essentially forming a tree.
+#
+# config.foo.bar=True
+# config.foobar=False
+#
+# turns into:
+# config.saved_value == {"foo": {"bar": "True"}, "foobar": "False"}
+#
+
+
+class ConfigSubsectionContent(object):
+ pass
+
+# we store a backup of the loaded configuration
+# data in self.stored_values, to be able to deploy
+# them when a new config element will be added,
+# so non-default values are instantly available
+
+# A list, for example:
+# config.dipswitches = ConfigSubList()
+# config.dipswitches.append(ConfigYesNo())
+# config.dipswitches.append(ConfigYesNo())
+# config.dipswitches.append(ConfigYesNo())
+class ConfigSubList(list, object):
+ def __init__(self):
+ object.__init__(self)
+ list.__init__(self)
+ self.stored_values = {}
+
+ def save(self):
+ for x in self:
+ x.save()
+
+ def load(self):
+ for x in self:
+ x.load()
+
+ def getSavedValue(self):
+ res = {}
+ for i in range(len(self)):
+ sv = self[i].saved_value
+ if sv is not None:
+ res[str(i)] = sv
+ return res
+
+ def setSavedValue(self, values):
+ self.stored_values = dict(values)
+ for (key, val) in self.stored_values.items():
+ if int(key) < len(self):
+ self[int(key)].saved_value = val
+
+ saved_value = property(getSavedValue, setSavedValue)
+
+ def append(self, item):
+ i = str(len(self))
+ list.append(self, item)
+ if i in self.stored_values:
+ item.saved_value = self.stored_values[i]
+ item.load()
+
+ def dict(self):
+ res = dict()
+ for index in range(len(self)):
+ res[str(index)] = self[index]
+ return res
+
+# same as ConfigSubList, just as a dictionary.
+# care must be taken that the 'key' has a proper
+# str() method, because it will be used in the config
+# file.
+class ConfigSubDict(dict, object):
+ def __init__(self):
+ object.__init__(self)
+ dict.__init__(self)
+ self.stored_values = {}
+
+ def save(self):
+ for x in self.values():
+ x.save()
+
+ def load(self):
+ for x in self.values():
+ x.load()
+
+ def getSavedValue(self):
+ res = {}
+ for (key, val) in self.items():
+ sv = val.saved_value
+ if sv is not None:
+ res[str(key)] = sv
+ return res
+
+ def setSavedValue(self, values):
+ self.stored_values = dict(values)
+ for (key, val) in self.items():
+ if str(key) in self.stored_values:
+ val = self.stored_values[str(key)]
+
+ saved_value = property(getSavedValue, setSavedValue)
+
+ def __setitem__(self, key, item):
+ dict.__setitem__(self, key, item)
+ if str(key) in self.stored_values:
+ item.saved_value = self.stored_values[str(key)]
+ item.load()
+
+ def dict(self):
+ return self
+
+# Like the classes above, just with a more "native"
+# syntax.
+#
+# some evil stuff must be done to allow instant
+# loading of added elements. this is why this class
+# is so complex.
+#
+# we need the 'content' because we overwrite
+# __setattr__.
+# If you don't understand this, try adding
+# __setattr__ to a usual exisiting class and you will.
+class ConfigSubsection(object):
+ def __init__(self):
+ object.__init__(self)
+ self.__dict__["content"] = ConfigSubsectionContent()
+ self.content.items = { }
+ self.content.stored_values = { }
+
+ def __setattr__(self, name, value):
+ if name == "saved_value":
+ return self.setSavedValue(value)
+ assert isinstance(value, ConfigSubsection) or isinstance(value, ConfigElement) or isinstance(value, ConfigSubList) or isinstance(value, ConfigSubDict), "ConfigSubsections can only store ConfigSubsections, ConfigSubLists, ConfigSubDicts or ConfigElements"
+ self.content.items[name] = value
+ if name in self.content.stored_values:
+ #print "ok, now we have a new item,", name, "and have the following value for it:", self.content.stored_values[name]
+ value.saved_value = self.content.stored_values[name]
+ value.load()
+
+ def __getattr__(self, name):
+ return self.content.items[name]
+
+ def getSavedValue(self):
+ res = self.content.stored_values
+ for (key, val) in self.content.items.items():
+ sv = val.saved_value
+ if sv is not None:
+ res[key] = sv
+ elif key in res:
+ del res[key]
+ return res
+
+ def setSavedValue(self, values):
+ values = dict(values)
+
+ self.content.stored_values = values
+
+ for (key, val) in self.content.items.items():
+ if key in values:
+ val.saved_value = values[key]
+
+ saved_value = property(getSavedValue, setSavedValue)
+
+ def save(self):
+ for x in self.content.items.values():
+ x.save()
+
+ def load(self):
+ for x in self.content.items.values():
+ x.load()
+
+ def dict(self):
+ return self.content.items
+
+# the root config object, which also can "pickle" (=serialize)
+# down the whole config tree.
+#
+# we try to keep non-existing config entries, to apply them whenever
+# a new config entry is added to a subsection
+# also, non-existing config entries will be saved, so they won't be
+# lost when a config entry disappears.
+class Config(ConfigSubsection):
+ def __init__(self):
+ ConfigSubsection.__init__(self)
+
+ def pickle_this(self, prefix, topickle, result):
+ for (key, val) in topickle.items():
+ name = prefix + "." + key
+
+ if isinstance(val, dict):
+ self.pickle_this(name, val, result)
+ elif isinstance(val, tuple):
+ result.append(name + "=" + val[0]) # + " ; " + val[1])
+ else:
+ result.append(name + "=" + val)
+
+ def pickle(self):
+ result = [ ]
+ self.pickle_this("config", self.saved_value, result)
+ return '\n'.join(result) + "\n"
+
+ def unpickle(self, lines):
+ tree = { }
+ for l in lines:
+ if not len(l) or l[0] == '#':
+ continue
+
+ n = l.find('=')
+ val = l[n+1:].strip()
+
+ names = l[:n].split('.')
+# if val.find(' ') != -1:
+# val = val[:val.find(' ')]
+
+ base = tree
+
+ for n in names[:-1]:
+ base = base.setdefault(n, {})
+
+ base[names[-1]] = val
+
+ # we inherit from ConfigSubsection, so ...
+ #object.__setattr__(self, "saved_value", tree["config"])
+ if "config" in tree:
+ self.setSavedValue(tree["config"])
+
+ def saveToFile(self, filename):
+ f = open(filename, "w")
+ f.write(self.pickle())
+ f.close()
+
+ def loadFromFile(self, filename):
+ f = open(filename, "r")
+ self.unpickle(f.readlines())
+ f.close()
+
+config = Config()
+config.misc = ConfigSubsection()
+
+class ConfigFile:
+ CONFIG_FILE = resolveFilename(SCOPE_CONFIG, "settings")
+
+ def load(self):
+ try:
+ config.loadFromFile(self.CONFIG_FILE)
+ except IOError, e:
+ print "unable to load config (%s), assuming defaults..." % str(e)
+
+ def save(self):
+# config.save()
+ config.saveToFile(self.CONFIG_FILE)
+
+ def __resolveValue(self, pickles, cmap):
+ if cmap.has_key(pickles[0]):
+ if len(pickles) > 1:
+ return self.__resolveValue(pickles[1:], cmap[pickles[0]].dict())
+ else:
+ return str(cmap[pickles[0]].value)
+ return None
+
+ def getResolvedKey(self, key):
+ names = key.split('.')
+ if len(names) > 1:
+ if names[0] == "config":
+ ret=self.__resolveValue(names[1:], config.content.items)
+ if ret and len(ret):
+ return ret
+ print "getResolvedKey", key, "failed !! (Typo??)"
+ return ""
+
+def NoSave(element):
+ element.disableSave()
+ return element
+
+configfile = ConfigFile()
+
+configfile.load()
+
+def getConfigListEntry(*args):
+ assert len(args) > 1, "getConfigListEntry needs a minimum of two arguments (descr, configElement)"
+ return args
+
+def updateConfigElement(element, newelement):
+ newelement.value = element.value
+ return newelement
+
+#def _(x):
+# return x
+#
+#config.bla = ConfigSubsection()
+#config.bla.test = ConfigYesNo()
+#config.nim = ConfigSubList()
+#config.nim.append(ConfigSubsection())
+#config.nim[0].bla = ConfigYesNo()
+#config.nim.append(ConfigSubsection())
+#config.nim[1].bla = ConfigYesNo()
+#config.nim[1].blub = ConfigYesNo()
+#config.arg = ConfigSubDict()
+#config.arg["Hello"] = ConfigYesNo()
+#
+#config.arg["Hello"].handleKey(KEY_RIGHT)
+#config.arg["Hello"].handleKey(KEY_RIGHT)
+#
+##config.saved_value
+#
+##configfile.save()
+#config.save()
+#print config.pickle()