source: orange/Orange/utils/environ.py @ 11456:96f4e75250e1

Revision 11456:96f4e75250e1, 10.4 KB checked in by Ales Erjavec <ales.erjavec@…>, 12 months ago (diff)

Changed the '_path_fix' function to preserve the order of non miktex entries in os.environPATH?.

Line 
1"""
2==============================================
3Orange environment configuration (``environ``)
4==============================================
5
6This module contains some basic customization options for Orange
7(for now mostly changing directories where orange settings are saved).
8
9How it works
10------------
11
12When this module is imported it will first load and parse a global
13configuration `orangerc.cfg` (located in the root directory of the orange
14installation). Further, it will look for and try to load a user specific
15configuration file located in $(HOME)/.orangerc.cfg or
16`application_dir`/orangerc.cfg where `application_dir` is a variable defined
17in the global configuration file.
18
19.. note:: in the configuration files all OS defined environment variables
20    (e.g $HOME, $USER, ...) are available.
21
22After all the parsing has taken place the select variables defined in the
23configuration will be made available as top level module variables.
24
25Example
26-------
27
28To change the location where settings are saved for Orange Canvas
29on Windows edit the global `orangerc.cfg` file and in the
30`[directories win32]` section change the `application_dir` variable:
31   
32    [directories win32]
33   
34    application_dir = D:/SharedAppData/orange/
35   
36In this way we can hard code the path instead of using the system default
37(defined in the the %APPDATA variable)
38
39Variables
40---------
41
42The following variables are exposed as top level module members
43
44`install_dir`:
45    Directory where Orange is installed.
46   
47`canvas_install_dir`:
48    Directory where Orange Canvas is installed.
49
50`widget_install_dir`:
51    Directory where Orange Widgets are installed.
52
53`icons_install_dir`:
54    Directory where icons for widgets are installed.
55
56`doc_install_dir`:
57    Directory with Orange documentation.
58 
59`dataset_install_dir`:
60    Directory with example data sets.
61
62`add_ons_dir`:
63    Directory where system-wide add-ons are installed
64   
65`add_ons_dir_user`:
66    Directory where user add-ons are installed
67   
68`application_dir`:
69    Directory where applications can save their data.
70     
71`output_dir`:
72    Directory where Orange saves settings/data.
73   
74`default_reports_dir`:
75    Directory where Orange Canvas saves the reports.
76   
77`orange_settings_dir`:
78    Directory where Orange settings are saved.
79   
80`canvas_settings_dir`:
81    Directory where Orange Canvas settings are saved.
82   
83`widget_settings_dir`:
84    Directory where Orange Widgets settings are saved.
85   
86`buffer_dir`:
87    Directory where :obj:`Orange.utils.serverfiles` downloads are stored. 
88
89`orange_no_deprecated_members`:
90    If True all deprecated members in Orange 2.5 will not be available.
91     
92"""
93
94import os
95import sys
96
97import ConfigParser
98import pkg_resources
99from pkg_resources import working_set
100
101
102def _path_fix():
103    """Fix some common problems with $(PATH) and sys.path
104    """
105    if os.name == "nt":
106        ## Move any miktex paths containing Qt's dll to the end of the %PATH%
107        paths = os.environ["PATH"].split(";")
108        paths = sorted(paths, key=lambda path: 1 if "miktex" in path else 0)
109        os.environ["PATH"] = ";".join(paths)
110
111    if sys.platform == "darwin":
112        ## PyQt4 installed from fink is installed in %{FINK_ROOT}lib/qt4-mac/lib/python${PYVERSION}/site-packages"
113        posible_fink_pyqt4_path = os.path.join(
114            sys.prefix, "lib/qt4-mac/lib/python" + sys.version[:3] + "/site-packages")
115        if os.path.exists(posible_fink_pyqt4_path):
116            sys.path.append(posible_fink_pyqt4_path)
117
118_path_fix()
119
120
121def _get_default_env():
122    """ Return a dictionary with default Orange environment."""
123
124    version = "orange"
125    version_display = "Orange 2.5"
126    orange_no_deprecated_members = "False"
127   
128    install_dir = os.path.dirname(os.path.abspath(__file__)) # Orange/misc
129    install_dir = os.path.dirname(install_dir) # Orange/
130
131    doc_install_dir = os.path.join(install_dir, "doc")
132    dataset_install_dir = os.path.join(install_dir, "datasets")
133
134    canvas_install_dir = os.path.join(install_dir, "OrangeCanvas")
135    widget_install_dir = os.path.join(install_dir, "OrangeWidgets")
136    icons_install_dir = os.path.join(widget_install_dir, "icons")
137    add_ons_dir = os.path.join(install_dir, "add-ons")
138
139    home = os.path.expanduser("~/")
140   
141    if sys.platform == "win32":
142        if home[-1] == ":":
143            home += "\\"
144        application_dir = os.environ["APPDATA"]
145        output_dir = os.path.join(application_dir, version)
146        default_reports_dir = os.path.join(home, "My Documents")
147    elif sys.platform == "darwin":
148        application_dir = os.path.join(home, "Library", "Application Support")
149        output_dir = os.path.join(application_dir, version)
150        default_reports_dir = os.path.join(home, "Documents")
151    else:
152        application_dir = home
153        output_dir = os.path.join(home, "." + version)
154       
155        documents = os.path.join(home, "Documents")
156        # Need to make sure Documents folder actually exists
157        if os.path.exists(documents) and os.path.isdir(documents):
158            default_reports_dir = documents
159        else:
160            default_reports_dir = home
161
162    add_ons_dir_user = os.path.join(output_dir, "add-ons")
163
164    orange_settings_dir = output_dir
165    canvas_settings_dir = os.path.join(output_dir, "OrangeCanvasQt4")
166    widget_settings_dir = os.path.join(output_dir, "widgetSettingsQt4")
167   
168    if sys.platform == "darwin":
169        buffer_dir = os.path.join(home, "Library", "Caches", version)
170    else:
171        buffer_dir = os.path.join(output_dir, "buffer")
172
173    return locals()
174
175_ALL_ENV_OPTIONS = ["version", "version_display", "is_canvas_installed",
176                    "orange_no_deprecated_members"]
177
178_ALL_DIR_OPTIONS = ["install_dir", "canvas_install_dir",
179                    "widget_install_dir", "icons_install_dir",
180                    "doc_install_dir", "dataset_install_dir", 
181                    "add_ons_dir", "add_ons_dir_user",
182                    "application_dir", "output_dir", "default_reports_dir",
183                    "orange_settings_dir", "canvas_settings_dir",
184                    "widget_settings_dir", "buffer_dir"]
185
186def get_platform_option(section, option):
187    """ Return the platform specific configuration `option` from `section`.
188    """
189    try:
190        return parser.get(section + " " + sys.platform, option)
191    except Exception:
192        return parser.get(section, option)
193
194#options read from environment variables
195_ENVIRON_OPTIONS = [ "orange_no_deprecated_members" ]
196
197def _configure_env(defaults=None):
198    """ Apply the configuration files on the default environment
199    and return the instance of SafeConfigParser
200     
201    """
202    if defaults is None:
203        defaults = dict(os.environ)
204        defaults.update(_get_default_env())
205
206    for opt in _ENVIRON_OPTIONS:
207        if opt in os.environ:
208            defaults[opt] = os.environ[opt]
209   
210    parser = ConfigParser.SafeConfigParser(defaults)
211    global_cfg = os.path.join(defaults["install_dir"], "orng", "orangerc.cfg")
212
213    if not parser.read([global_cfg]):
214        pass
215#        import warnings
216#        warnings.warn("Could not read global orange configuration file.")
217
218    # In case the global_cfg does not exist or is empty
219    if not parser.has_section("directories"):
220        parser.add_section("directories")
221    if not parser.has_section("Orange"):
222        parser.add_section("Orange")
223       
224    platform = sys.platform
225    try:
226        application_dir = parser.get("directories " + platform, "application_dir")
227    except Exception:
228        application_dir = parser.get("directories", "application_dir")
229   
230    parser.read([os.path.join(application_dir, "orangerc.cfg"),
231                 os.path.expanduser("~/.orangerc.cfg")])
232   
233    return parser
234
235parser = _configure_env()
236
237for dirname in _ALL_DIR_OPTIONS:
238    globals()[dirname] = get_platform_option("directories", dirname)
239   
240
241if not os.path.isdir(widget_install_dir) or not os.path.isdir(widget_install_dir):
242    # Canvas and widgets are not installed
243    canvas_install_dir = None
244    widget_install_dir = None
245    canvas_settings_dir = None
246    widget_settings_dir = None
247    is_canvas_installed = False
248else:
249    is_canvas_installed = True
250   
251if not os.path.isdir(icons_install_dir):
252    icons_install_dir = ""
253   
254version = parser.get("Orange", "version")
255version_display = parser.get("Orange", "version_display")
256orange_no_deprecated_members = parser.getboolean("Orange", "orange_no_deprecated_members")
257version = get_platform_option("Orange", "version")
258   
259# Create the directories if missing
260# TODO: This are not needed if using orange without the GUI
261
262_directories_to_create = ["application_dir", "orange_settings_dir",
263        "buffer_dir", "widget_settings_dir", "canvas_settings_dir"]
264
265for dname in _directories_to_create:
266    dname = globals()[dname]
267    if dname is not None and not os.path.isdir(dname):
268        try:
269            os.makedirs(dname)        # Vista has roaming profiles that will say that this folder does not exist and will then fail to create it, because it exists...
270        except Exception:
271            pass
272       
273def samepath(path1, path2):
274    """ Do the paths path1 and path2 point to the same location.
275    """
276    return os.path.normcase(os.path.realpath(os.path.normpath(path1))) == \
277           os.path.normcase(os.path.realpath(os.path.normpath(path2)))
278
279def add_orange_directories_to_path():
280    """Add orange directory paths to sys.path."""
281
282    paths_to_add = [] #[install_dir]
283
284    if canvas_install_dir is not None:
285        paths_to_add.append(canvas_install_dir)
286
287    # Instead of doing this OrangeWidgets should be a package
288    if widget_install_dir is not None and os.path.isdir(widget_install_dir):
289        paths_to_add.append(widget_install_dir)
290        default_widgets_dirs = [os.path.join(widget_install_dir, x) \
291                                for x in os.listdir(widget_install_dir) \
292                                if os.path.isdir(os.path.join(widget_install_dir, x))]
293        paths_to_add.extend(default_widgets_dirs)
294
295    for path in paths_to_add:
296        if os.path.isdir(path) and not any([samepath(path, x) for x in sys.path]):
297            sys.path.insert(0, path)
298           
299add_orange_directories_to_path()
300directories = dict([(dname, globals()[dname]) for dname in _ALL_DIR_OPTIONS])
301
302def load_eggs(search_path):
303    distributions, errors = working_set.find_plugins(
304        pkg_resources.Environment(search_path)
305    )
306    map(working_set.add, distributions)
307
308    if errors:
309        import warnings
310        warnings.warn("Error loading eggs: %s" % (errors,))
311
312load_eggs([add_ons_dir_user])
Note: See TracBrowser for help on using the repository browser.