Utils for dynamically loading themes.
[electrum-nvc.git] / lib / util.py
1 import os
2 import platform
3 import sys
4
5 def print_error(*args):
6     for item in args:
7       sys.stderr.write(str(item))
8     sys.stderr.write("\n")
9     sys.stderr.flush()
10
11 def appdata_dir():
12     if platform.system() == "Windows":
13         return os.path.join(os.environ["APPDATA"], "Electrum")
14     elif platform.system() == "Linux":
15         return os.path.join(sys.prefix, "share", "electrum")
16     elif (platform.system() == "Darwin" or
17           platform.system() == "DragonFly"):
18         return "/Library/Application Support/Electrum"
19     else:
20         raise Exception("Unknown system")
21
22 def get_resource_path(*args):
23     return os.path.join(".", *args)
24
25 def local_data_dir():
26     assert sys.argv
27     prefix_path = os.path.dirname(sys.argv[0])
28     local_data = os.path.join(prefix_path, "data")
29     return local_data
30
31 def load_theme_name(theme_path):
32     try:
33         with open(os.path.join(theme_path, "name.cfg")) as name_cfg_file:
34             return name_cfg_file.read().rstrip("\n").strip()
35     except IOError:
36         return None
37
38 def theme_dirs_from_prefix(prefix):
39     if not os.path.exists(prefix):
40         return []
41     theme_paths = {}
42     for potential_theme in os.listdir(prefix):
43         theme_full_path = os.path.join(prefix, potential_theme)
44         theme_css = os.path.join(theme_full_path, "style.css")
45         if not os.path.exists(theme_css):
46             continue
47         theme_name = load_theme_name(theme_full_path)
48         if theme_name is None:
49             continue
50         theme_paths[theme_name] = prefix, potential_theme
51     return theme_paths
52
53 def load_theme_paths():
54     theme_paths = {}
55     prefixes = (local_data_dir(), appdata_dir())
56     for prefix in prefixes:
57         theme_paths.update(theme_dirs_from_prefix(prefix))
58     return theme_paths
59