access to global configuration using set_config and get_config
[electrum-nvc.git] / lib / simple_config.py
index 90686af..30c7f9d 100644 (file)
@@ -1,88 +1,98 @@
-import json, ast
-import os, ast
-from util import user_dir
+import json
+import ast
+import threading
+import os
 
-from version import ELECTRUM_VERSION, SEED_VERSION
+from util import user_dir, print_error, print_msg
 
 
-# old stuff.. should be removed at some point
-def replace_keys(obj, old_key, new_key):
-    if isinstance(obj, dict):
-        if old_key in obj:
-            obj[new_key] = obj[old_key]
-            del obj[old_key]
-        for elem in obj.itervalues():
-            replace_keys(elem, old_key, new_key)
-    elif isinstance(obj, list):
-        for elem in obj:
-            replace_keys(elem, old_key, new_key)
-
-def old_to_new(d):
-    replace_keys(d, 'blk_hash', 'block_hash')
-    replace_keys(d, 'pos', 'index')
-    replace_keys(d, 'nTime', 'timestamp')
-    replace_keys(d, 'is_in', 'is_input')
-    replace_keys(d, 'raw_scriptPubKey', 'raw_output_script')
+config = None
+def get_config():
+    global config
+    return config
 
+def set_config(c):
+    global config
+    config = c
 
 
 class SimpleConfig:
-
-    def __init__(self, options=None):
-
-        self.wallet_config = {}
-        if options:
-            # this will call read_wallet_config only if there is a wallet_path value in options
-            try:
-                self.read_wallet_config(options.wallet_path)
-            except:
-                pass
-            
+    """
+The SimpleConfig class is responsible for handling operations involving
+configuration files.  The constructor reads and stores the system and 
+user configurations from electrum.conf into separate dictionaries within
+a SimpleConfig instance then reads the wallet file.
+"""
+    def __init__(self, options={}):
+        self.lock = threading.Lock()
 
         # system conf, readonly
         self.system_config = {}
-        self.read_system_config()
+        if options.get('portable') is not True:
+            self.read_system_config()
+
+        # command-line options
+        self.options_config = options
+
+        # init path
+        self.init_path()
 
         # user conf, writeable
         self.user_config = {}
         self.read_user_config()
 
-        # command-line options
-        self.options_config = {}
-        if options:
-            if options.server: self.options_config['server'] = options.server
-            if options.proxy: self.options_config['proxy'] = options.proxy
-            if options.gui: self.options_config['gui'] = options.gui
-            
-        
+        set_config(self)
+
+
+
+    def init_path(self):
 
-    def set_key(self, key, value, save = False):
+        # Read electrum path in the command line configuration
+        self.path = self.options_config.get('electrum_path')
+
+        # Read electrum path in the system configuration
+        if self.path is None:
+            self.path = self.system_config.get('electrum_path')
+
+        # If not set, use the user's default data directory.
+        if self.path is None:
+            self.path = user_dir()
+
+        # Make directory if it does not yet exist.
+        if not os.path.exists(self.path):
+            os.mkdir(self.path)
+
+        print_error( "electrum directory", self.path)
+
+        # portable wallet: use the same directory for wallet and headers file
+        #if options.get('portable'):
+        #    self.wallet_config['blockchain_headers_path'] = os.path.dirname(self.path)
+            
+    def set_key(self, key, value, save = True):
         # find where a setting comes from and save it there
-        if self.options_config.get(key):
+        if self.options_config.get(key) is not None:
+            print "Warning: not changing '%s' because it was passed as a command-line option"%key
             return
 
-        elif self.user_config.get(key):
-            self.user_config[key] = value
-            if save: self.save_user_config()
-
-        elif self.system_config.get(key):
+        elif self.system_config.get(key) is not None:
             if str(self.system_config[key]) != str(value):
                 print "Warning: not changing '%s' because it was set in the system configuration"%key
 
-        elif self.wallet_config.get(key):
-            self.wallet_config[key] = value
-            if save: self.save_wallet_config()
-
         else:
-            # add key to wallet config
-            self.wallet_config[key] = value
-            if save: self.save_wallet_config()
+
+            with self.lock:
+                self.user_config[key] = value
+                if save: 
+                    self.save_user_config()
+
 
 
     def get(self, key, default=None):
+
+        out = None
+
         # 1. command-line options always override everything
-        if self.options_config.has_key(key):
-            # print "found", key, "in options"
+        if self.options_config.has_key(key) and self.options_config.get(key) is not None:
             out = self.options_config.get(key)
 
         # 2. user configuration 
@@ -93,22 +103,23 @@ class SimpleConfig:
         elif self.system_config.has_key(key):
             out = self.system_config.get(key)
 
-        # 3. use the wallet file config
-        else:
-            out = self.wallet_config.get(key)
-
         if out is None and default is not None:
             out = default
 
         # try to fix the type
         if default is not None and type(out) != type(default):
             import ast
-            out = ast.literal_eval(out)
-            
+            try:
+                out = ast.literal_eval(out)
+            except Exception:
+                print "type error for '%s': using default value"%key
+                out = default
+
         return out
 
 
     def is_modifiable(self, key):
+        """Check if the config file is modifiable."""
         if self.options_config.has_key(key):
             return False
         elif self.user_config.has_key(key):
@@ -120,11 +131,12 @@ class SimpleConfig:
 
 
     def read_system_config(self):
+        """Parse and store the system config settings in electrum.conf into system_config[]."""
         name = '/etc/electrum.conf'
         if os.path.exists(name):
             try:
                 import ConfigParser
-            except:
+            except ImportError:
                 print "cannot parse electrum.conf. please install ConfigParser"
                 return
                 
@@ -138,81 +150,33 @@ class SimpleConfig:
 
 
     def read_user_config(self):
-        name = os.path.join( user_dir(), 'electrum.conf')
-        if os.path.exists(name):
+        """Parse and store the user config settings in electrum.conf into user_config[]."""
+        if not self.path: return
+
+        path = os.path.join(self.path, "config")
+        if os.path.exists(path):
             try:
-                import ConfigParser
-            except:
-                print "cannot parse electrum.conf. please install ConfigParser"
+                with open(path, "r") as f:
+                    data = f.read()
+            except IOError:
                 return
-                
-            p = ConfigParser.ConfigParser()
-            p.read(name)
             try:
-                for k, v in p.items('client'):
-                    self.user_config[k] = v
-            except ConfigParser.NoSectionError:
-                pass
-
-
-    def init_path(self, wallet_path):
-        """Set the path of the wallet."""
-        if wallet_path is not None:
-            self.path = wallet_path
-            return
-
-        # Look for wallet file in the default data directory.
-        # Keeps backwards compatibility.
-        wallet_dir = user_dir()
+                d = ast.literal_eval( data )  #parse raw data from reading wallet file
+            except Exception:
+                print_msg("Error: Cannot read config file.")
+                return
 
-        # Make wallet directory if it does not yet exist.
-        if not os.path.exists(wallet_dir):
-            os.mkdir(wallet_dir)
-        self.path = os.path.join(wallet_dir, "electrum.dat")
+            self.user_config = d
 
 
     def save_user_config(self):
-        import ConfigParser
-        config = ConfigParser.RawConfigParser()
-        config.add_section('client')
-        for k,v in self.user_config.items():
-            config.set('client', k, v)
-
-        with open( os.path.join( user_dir(), 'electrum.conf'), 'wb') as configfile:
-            config.write(configfile)
-        
-
-
-
-    def read_wallet_config(self, path):
-        """Read the contents of the wallet file."""
-        self.wallet_file_exists = False
-        self.init_path(path)
-        try:
-            with open(self.path, "r") as f:
-                data = f.read()
-        except IOError:
-            return
-        try:
-            d = ast.literal_eval( data )  #parse raw data from reading wallet file
-            old_to_new(d)
-        except:
-            raise IOError("Cannot read wallet file.")
+        if not self.path: return
 
-        self.wallet_config = d
-        self.wallet_file_exists = True
-
-
-
-    def save(self):
-        self.save_wallet_config()
-
-
-    def save_wallet_config(self):
-        s = repr(self.wallet_config)
-        f = open(self.path,"w")
+        path = os.path.join(self.path, "config")
+        s = repr(self.user_config)
+        f = open(path,"w")
         f.write( s )
         f.close()
-        import stat
-        os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
-
+        if self.get('gui') != 'android':
+            import stat
+            os.chmod(path, stat.S_IREAD | stat.S_IWRITE)