source: orange/orange/misc/environ.py @ 9669:165371b04b4a

Revision 9669:165371b04b4a, 10.5 KB checked in by anze <anze.staric@…>, 2 years ago (diff)

Moved content of Orange dir to package dir

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`network_install_dir`:
63    Directory with example networks.
64
65`add_ons_dir`:
66    Directory where system-wide add-ons are installed
67   
68`add_ons_dir_user`:
69    Directory where user add-ons are installed
70   
71`application_dir`:
72    Directory where applications can save their data.
73     
74`output_dir`:
75    Directory where Orange saves settings/data.
76   
77`default_reports_dir`:
78    Directory where Orange Canvas saves the reports.
79   
80`orange_settings_dir`:
81    Directory where Orange settings are saved.
82   
83`canvas_settings_dir`:
84    Directory where Orange Canvas settings are saved.
85   
86`widget_settings_dir`:
87    Directory where Orange Widgets settings are saved.
88   
89`buffer_dir`:
90    Directory where :obj:`Orange.misc.serverfiles` downloads are stored. 
91
92`orange_no_deprecated_members`:
93    If True all deprecated members in Orange 2.5 will not be available.
94     
95"""
96
97import os, sys
98import ConfigParser
99
100def _path_fix():
101    """ Fix some common problems with $(PATH) and sys.path
102    """
103    if os.name == "nt":
104        ## Move any miktex paths containing Qt's dll to the end of the %PATH%
105        paths = os.environ["PATH"].split(";")
106        paths.sort(lambda x,y: -1 if "PyQt4" in x else (1 if "miktex" in y and \
107                        os.path.exists(os.path.join(y, "QtCore4.dll")) else 0))
108        os.environ["PATH"] = ";".join(paths)
109       
110    if sys.platform == "darwin":
111        ## PyQt4 installed from fink is installed in %{FINK_ROOT}lib/qt4-mac/lib/python${PYVERSION}/site-packages"
112        posible_fink_pyqt4_path = os.path.join(sys.prefix, 
113                "lib/qt4-mac/lib/python" + sys.version[:3] + "/site-packages")
114        if os.path.exists(posible_fink_pyqt4_path):
115            sys.path.append(posible_fink_pyqt4_path)
116           
117_path_fix()
118
119def _get_default_env():
120    """ Return a dictionary with default Orange environment."""
121
122    version = "orange"
123    version_display = "Orange 2.5"
124    orange_no_deprecated_members = "False"
125   
126    try:
127        install_dir = os.path.dirname(os.path.abspath(__file__)) # Orange/misc
128        install_dir = os.path.dirname(install_dir) # Orange/
129        install_dir = os.path.dirname(install_dir) #
130    except Exception: # Why should this happen??
131        raise
132        import orange
133        install_dir = os.path.dirname(os.path.abspath(orange.__file__))
134
135    doc_install_dir = os.path.join(install_dir, "doc") 
136    dataset_install_dir = os.path.join(install_dir, "doc", "datasets") 
137    network_install_dir = os.path.join(install_dir, "doc", "networks")
138
139    canvas_install_dir = os.path.join(install_dir, "OrangeCanvas")
140    widget_install_dir = os.path.join(install_dir, "OrangeWidgets")
141    icons_install_dir = os.path.join(widget_install_dir, "icons")
142    add_ons_dir = os.path.join(install_dir, "add-ons")
143
144    home = os.path.expanduser("~/")
145   
146    if sys.platform == "win32":
147        if home[-1] == ":":
148            home += "\\"
149        application_dir = os.environ["APPDATA"]
150        output_dir = os.path.join(application_dir, version)
151        default_reports_dir = os.path.join(home, "My Documents")
152    elif sys.platform == "darwin":
153        application_dir = os.path.join(home, "Library", "Application Support")
154        output_dir = os.path.join(application_dir, version)
155        default_reports_dir = os.path.join(home, "Documents")
156    else:
157        application_dir = home
158        output_dir = os.path.join(home, "." + version)
159       
160        documents = os.path.join(home, "Documents")
161        # Need to make sure Documents folder actually exists
162        if os.path.exists(documents) and os.path.isdir(documents):
163            default_reports_dir = documents
164        else:
165            default_reports_dir = home
166
167    add_ons_dir_user = os.path.join(output_dir, "add-ons")
168
169    orange_settings_dir = output_dir
170    canvas_settings_dir = os.path.join(output_dir, "OrangeCanvasQt4")
171    widget_settings_dir = os.path.join(output_dir, "widgetSettingsQt4")
172   
173    if sys.platform == "darwin":
174        buffer_dir = os.path.join(home, "Library", "Caches", version)
175    else:
176        buffer_dir = os.path.join(output_dir, "buffer")
177
178    return locals()
179
180_ALL_ENV_OPTIONS = ["version", "version_display", "is_canvas_installed",
181                    "orange_no_deprecated_members"]
182
183_ALL_DIR_OPTIONS = ["install_dir", "canvas_install_dir",
184                    "widget_install_dir", "icons_install_dir",
185                    "doc_install_dir", "dataset_install_dir", 
186                    "network_install_dir", "add_ons_dir", "add_ons_dir_user",
187                    "application_dir", "output_dir", "default_reports_dir",
188                    "orange_settings_dir", "canvas_settings_dir",
189                    "widget_settings_dir", "buffer_dir"]
190
191def get_platform_option(section, option):
192    """ Return the platform specific configuration `option` from `section`.
193    """
194    try:
195        return parser.get(section + " " + sys.platform, option)
196    except Exception:
197        return parser.get(section, option)
198
199#options read from environment variables
200_ENVIRON_OPTIONS = [ "orange_no_deprecated_members" ]
201
202def _configure_env(defaults=None):
203    """ Apply the configuration files on the default environment
204    and return the instance of SafeConfigParser
205     
206    """
207    if defaults is None:
208        defaults = dict(os.environ)
209        defaults.update(_get_default_env())
210
211    for opt in _ENVIRON_OPTIONS:
212        if opt in os.environ:
213            defaults[opt] = os.environ[opt]
214   
215    parser = ConfigParser.SafeConfigParser(defaults)
216    global_cfg = os.path.join(defaults["install_dir"], "orangerc.cfg")
217    if not parser.read([global_cfg]):
218        pass
219#        import warnings
220#        warnings.warn("Could not read global orange configuration file.")
221
222    # In case the global_cfg does not exist or is empty
223    if not parser.has_section("directories"):
224        parser.add_section("directories")
225    if not parser.has_section("Orange"):
226        parser.add_section("Orange")
227       
228    platform = sys.platform
229    try:
230        application_dir = parser.get("directories " + platform, "application_dir")
231    except Exception:
232        application_dir = parser.get("directories", "application_dir")
233   
234    parser.read([os.path.join(application_dir, "orangerc.cfg"),
235                 os.path.expanduser("~/.orangerc.cfg")])
236   
237    return parser
238
239parser = _configure_env()
240
241for dirname in _ALL_DIR_OPTIONS:
242    globals()[dirname] = get_platform_option("directories", dirname)
243   
244
245if not os.path.isdir(widget_install_dir) or not os.path.isdir(widget_install_dir):
246    # Canvas and widgets are not installed
247    canvas_install_dir = None
248    widget_install_dir = None
249    canvas_settings_dir = None
250    widget_settings_dir = None
251    is_canvas_installed = False
252else:
253    is_canvas_installed = True
254   
255if not os.path.isdir(icons_install_dir):
256    icons_install_dir = ""
257   
258version = parser.get("Orange", "version")
259version_display = parser.get("Orange", "version_display")
260orange_no_deprecated_members = parser.getboolean("Orange", "orange_no_deprecated_members")
261version = get_platform_option("Orange", "version")
262   
263# Create the directories if missing
264# TODO: This are not needed if using orange without the GUI
265
266_directories_to_create = ["application_dir", "orange_settings_dir",
267        "buffer_dir", "widget_settings_dir", "canvas_settings_dir"]
268
269for dname in _directories_to_create:
270    dname = globals()[dname]
271    if dname is not None and not os.path.isdir(dname):
272        try:
273            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...
274        except Exception:
275            pass
276       
277def samepath(path1, path2):
278    """ Do the paths path1 and path2 point to the same location.
279    """
280    return os.path.normcase(os.path.realpath(os.path.normpath(path1))) == \
281           os.path.normcase(os.path.realpath(os.path.normpath(path2)))
282
283def add_orange_directories_to_path():
284    """Add orange directory paths to sys.path."""
285    paths_to_add = [install_dir]
286
287    if canvas_install_dir is not None:
288        paths_to_add.append(canvas_install_dir)
289
290    # Instead of doing this OrangeWidgets should be a package
291    if widget_install_dir is not None and os.path.isdir(widget_install_dir):
292        paths_to_add.append(widget_install_dir)
293        default_widgets_dirs = [os.path.join(widget_install_dir, x) \
294                                for x in os.listdir(widget_install_dir) \
295                                if os.path.isdir(os.path.join(widget_install_dir, x))]
296        paths_to_add.extend(default_widgets_dirs)
297
298    for path in paths_to_add:
299        if os.path.isdir(path) and not any([samepath(path, x) for x in sys.path]):
300            sys.path.insert(0, path)
301           
302add_orange_directories_to_path()
303directories = dict([(dname, globals()[dname]) for dname in _ALL_DIR_OPTIONS])
Note: See TracBrowser for help on using the repository browser.