File: config.py

package info (click to toggle)
python-vispy 0.15.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,868 kB
  • sloc: python: 59,799; javascript: 6,800; makefile: 69; sh: 6
file content (490 lines) | stat: -rw-r--r-- 15,457 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

"""Vispy configuration functions."""

import io
import os
from os import path as op
import inspect
import json
import sys
import platform
import getopt
import traceback
import tempfile
import atexit
from shutil import rmtree

import numpy as np

from .event import EmitterGroup, EventEmitter, Event
from .logs import logger, set_log_level, use_log_level

file_types = [io.TextIOWrapper, io.BufferedRandom]
try:
    file_types += [tempfile._TemporaryFileWrapper]  # Py3k Windows this happens
except Exception:
    pass
file_types = tuple(file_types)

config = None
_data_path = None
_allowed_config_keys = None


def _init():
    """Create global Config object, parse command flags."""
    global config, _data_path, _allowed_config_keys

    app_dir = _get_vispy_app_dir()
    if app_dir is not None:
        _data_path = op.join(app_dir, 'data')
        _test_data_path = op.join(app_dir, 'test_data')
    else:
        _data_path = _test_data_path = None

    # All allowed config keys and the types they may have
    _allowed_config_keys = {
        'data_path': (str,),
        'default_backend': (str,),
        'gl_backend': (str,),
        'gl_debug': (bool,),
        'glir_file': (str,) + file_types,
        'include_path': list,
        'logging_level': (str,),
        'qt_lib': (str,),
        'dpi': (int, type(None)),
        'profile': (str, type(None),),
        'audit_tests': (bool,),
        'test_data_path': (str, type(None),),
    }

    # Default values for all config options
    default_config_options = {
        'data_path': _data_path,
        'default_backend': '',
        'gl_backend': 'gl2',
        'gl_debug': False,
        'glir_file': '',
        'include_path': [],
        'logging_level': 'warning',
        'qt_lib': 'any',
        'dpi': None,
        'profile': None,
        'audit_tests': False,
        'test_data_path': _test_data_path,
    }

    config = Config(**default_config_options)

    try:
        config.update(**_load_config())
    except Exception as err:
        raise Exception('Error while reading vispy config file "%s":\n  %s' %
                        (_get_config_fname(), str(err)))
    set_log_level(config['logging_level'])

    _parse_command_line_arguments()


###############################################################################
# Command line flag parsing

VISPY_HELP = """
VisPy command line arguments:

  --vispy-backend=(qt|pyqt4|pyqt5|pyqt6|pyside|pyside2|pyside6|glfw|pyglet|sdl2|wx)
    Selects the backend system for VisPy to use. This will override the default
    backend selection in your configuration file.

  --vispy-log=(debug|info|warning|error|critical)[,search string]
    Sets the verbosity of logging output. The default is 'warning'. If a search
    string is given, messages will only be displayed if they match the string,
    or if their call location (module.class:method(line) or
    module:function(line)) matches the string.

  --vispy-dpi=resolution
    Force the screen resolution to a certain value (in pixels per inch). By
    default, the OS is queried to determine the screen DPI.

  --vispy-fps
    Print the framerate (in Frames Per Second) in the console.

  --vispy-gl-debug
    Enables error checking for all OpenGL calls.

  --vispy-glir-file
    Export glir commands to specified file.

  --vispy-profile=locations
    Measure performance at specific code locations and display results.
    *locations* may be "all" or a comma-separated list of method names like
    "SceneCanvas.draw_visual".

  --vispy-cprofile
    Enable profiling using the built-in cProfile module and display results
    when the program exits.

  --vispy-audit-tests
    Enable user auditing of image test results.

  --vispy-help
    Display this help message.

"""


def _parse_command_line_arguments():
    """Transform vispy specific command line args to vispy config.
    Put into a function so that any variables dont leak in the vispy namespace.
    """
    global config
    # Get command line args for vispy
    argnames = ['vispy-backend=', 'vispy-gl-debug', 'vispy-glir-file=',
                'vispy-log=', 'vispy-help', 'vispy-profile=', 'vispy-cprofile',
                'vispy-dpi=', 'vispy-audit-tests']
    try:
        opts, args = getopt.getopt(sys.argv[1:], '', argnames)
    except getopt.GetoptError:
        opts = []
    # Use them to set the config values
    for o, a in opts:
        if o.startswith('--vispy'):
            if o == '--vispy-backend':
                config['default_backend'] = a
                logger.info('vispy backend: %s', a)
            elif o == '--vispy-gl-debug':
                config['gl_debug'] = True
            elif o == '--vispy-glir-file':
                config['glir_file'] = a
            elif o == '--vispy-log':
                if ',' in a:
                    verbose, match = a.split(',')
                else:
                    verbose = a
                    match = None
                config['logging_level'] = a
                set_log_level(verbose, match)
            elif o == '--vispy-profile':
                config['profile'] = a
            elif o == '--vispy-cprofile':
                _enable_profiling()
            elif o == '--vispy-help':
                print(VISPY_HELP)
            elif o == '--vispy-dpi':
                config['dpi'] = int(a)
            elif o == '--vispy-audit-tests':
                config['audit_tests'] = True
            else:
                logger.warning("Unsupported vispy flag: %s" % o)


###############################################################################
# CONFIG

# Adapted from pyzolib/paths.py:
# https://bitbucket.org/pyzo/pyzolib/src/tip/paths.py
def _get_vispy_app_dir():
    """Helper to get the default directory for storing vispy data"""
    # Define default user directory
    user_dir = os.path.expanduser('~')

    # Get system app data dir
    path = None
    if sys.platform.startswith('win'):
        path1, path2 = os.getenv('LOCALAPPDATA'), os.getenv('APPDATA')
        path = path1 or path2
    elif sys.platform.startswith('darwin'):
        path = os.path.join(user_dir, 'Library', 'Application Support')
    # On Linux and as fallback
    if not (path and os.path.isdir(path)):
        path = user_dir

    # Maybe we should store things local to the executable (in case of a
    # portable distro or a frozen application that wants to be portable)
    prefix = sys.prefix
    if getattr(sys, 'frozen', None):  # See application_dir() function
        prefix = os.path.abspath(os.path.dirname(sys.path[0]))
    for reldir in ('settings', '../settings'):
        localpath = os.path.abspath(os.path.join(prefix, reldir))
        if os.path.isdir(localpath):
            try:
                open(os.path.join(localpath, 'test.write'), 'wb').close()
                os.remove(os.path.join(localpath, 'test.write'))
            except IOError:
                pass  # We cannot write in this directory
            else:
                path = localpath
                break

    # Get path specific for this app
    appname = '.vispy' if path == user_dir else 'vispy'
    path = os.path.join(path, appname)
    return path


class ConfigEvent(Event):
    """Event indicating a configuration change.

    This class has a 'changes' attribute which is a dict of all name:value
    pairs that have changed in the configuration.
    """

    def __init__(self, changes):
        Event.__init__(self, type='config_change')
        self.changes = changes


class Config(object):
    """Container for global settings used application-wide in vispy.

    Events:

    - Config.events.changed - Emits ConfigEvent whenever the configuration changes.

    """

    def __init__(self, **kwargs):
        self.events = EmitterGroup(source=self)
        self.events['changed'] = EventEmitter(
            event_class=ConfigEvent,
            source=self)
        self._config = {}
        self.update(**kwargs)
        self._known_keys = get_config_keys()

    def __getitem__(self, item):
        return self._config[item]

    def __setitem__(self, item, val):
        self._check_key_val(item, val)
        self._config[item] = val
        # inform any listeners that a configuration option has changed
        self.events.changed(changes={item: val})

    def _check_key_val(self, key, val):
        global _allowed_config_keys
        # check values against acceptable ones
        known_keys = _allowed_config_keys
        if key not in known_keys:
            raise KeyError('key "%s" not in known keys: "%s"'
                           % (key, known_keys))
        if not isinstance(val, known_keys[key]):
            raise TypeError('Value for key "%s" must be one of %s, not %s.'
                            % (key, known_keys[key], type(val)))

    def update(self, **kwargs):
        for key, val in kwargs.items():
            self._check_key_val(key, val)
        self._config.update(kwargs)
        self.events.changed(changes=kwargs)

    def __repr__(self):
        return repr(self._config)


def get_config_keys():
    """The config keys known by vispy and their allowed data types.

    Returns
    -------
    keys : dict
        Dict of {key: (types,)} pairs.
    """
    global _allowed_config_keys
    return _allowed_config_keys.copy()


def _get_config_fname():
    """Helper for the vispy config file"""
    directory = _get_vispy_app_dir()
    if directory is None:
        return None
    fname = op.join(directory, 'vispy.json')
    if os.environ.get('_VISPY_CONFIG_TESTING', None) is not None:
        fname = op.join(_TempDir(), 'vispy.json')
    return fname


def _load_config():
    """Helper to load prefs from ~/.vispy/vispy.json"""
    fname = _get_config_fname()
    if fname is None or not op.isfile(fname):
        return dict()
    with open(fname, 'r') as fid:
        config = json.load(fid)
    return config


def save_config(**kwargs):
    """Save configuration keys to vispy config file

    Parameters
    ----------
    **kwargs : keyword arguments
        Key/value pairs to save to the config file.
    """
    if kwargs == {}:
        kwargs = config._config
    current_config = _load_config()
    current_config.update(**kwargs)
    # write to disk
    fname = _get_config_fname()
    if fname is None:
        raise RuntimeError('config filename could not be determined')
    if not op.isdir(op.dirname(fname)):
        os.mkdir(op.dirname(fname))
    with open(fname, 'w') as fid:
        json.dump(current_config, fid, sort_keys=True, indent=0)


def set_data_dir(directory=None, create=False, save=False):
    """Set vispy data download directory

    Parameters
    ----------
    directory : str | None
        The directory to use.
    create : bool
        If True, create directory if it doesn't exist.
    save : bool
        If True, save the configuration to the vispy config.
    """
    if directory is None:
        directory = _data_path
        if _data_path is None:
            raise IOError('default path cannot be determined, please '
                          'set it manually (directory != None)')
    if not op.isdir(directory):
        if not create:
            raise IOError('directory "%s" does not exist, perhaps try '
                          'create=True to create it?' % directory)
        os.mkdir(directory)
    config.update(data_path=directory)
    if save:
        save_config(data_path=directory)


def _enable_profiling():
    """Start profiling and register callback to print stats when the program
    exits.
    """
    import cProfile
    import atexit
    global _profiler
    _profiler = cProfile.Profile()
    _profiler.enable()
    atexit.register(_profile_atexit)


_profiler = None


def _profile_atexit():
    global _profiler
    _profiler.print_stats(sort='cumulative')


def sys_info(fname=None, overwrite=False):
    """Get relevant system and debugging information

    Parameters
    ----------
    fname : str | None
        Filename to dump info to. Use None to simply print.
    overwrite : bool
        If True, overwrite file (if it exists).

    Returns
    -------
    out : str
        The system information as a string.
    """
    if fname is not None and op.isfile(fname) and not overwrite:
        raise IOError('file exists, use overwrite=True to overwrite')

    out = 'Platform: %s\n' % platform.platform()
    out += 'Python:   %s\n' % str(sys.version).replace('\n', ' ')
    out += 'NumPy:    %s\n' % (np.__version__,)
    try:
        # Nest all imports here to avoid any circular imports
        from ..app import use_app, Canvas
        from ..app.backends import BACKEND_NAMES
        from ..gloo import gl
        from .check_environment import has_backend
        # get default app
        with use_log_level('warning'):
            app = use_app(call_reuse=False)  # suppress messages
        out += 'Backend:  %s\n' % app.backend_name
        for backend in BACKEND_NAMES:
            if backend.startswith('ipynb_'):
                continue
            with use_log_level('warning', print_msg=False):
                which = has_backend(backend, out=['which'])[1]
            out += '{0:<9} {1}\n'.format(backend + ':', which)
        out += '\n'
        # We need an OpenGL context to get GL info
        canvas = Canvas('Test', (10, 10), show=False, app=app)
        canvas._backend._vispy_set_current()
        out += 'GL version:  %r\n' % (gl.glGetParameter(gl.GL_VERSION),)
        x_ = gl.GL_MAX_TEXTURE_SIZE
        out += 'MAX_TEXTURE_SIZE: %r\n' % (gl.glGetParameter(x_),)
        out += 'Extensions: %r\n' % (gl.glGetParameter(gl.GL_EXTENSIONS),)
        canvas.close()
    except Exception:  # don't stop printing info
        out += 'App info-gathering error:\n%s' % traceback.format_exc()
        pass
    if fname is not None:
        with open(fname, 'w') as fid:
            fid.write(out)
    return out


class _TempDir(str):
    """Class for creating and auto-destroying temp dir

    This is designed to be used with testing modules.

    We cannot simply use __del__() method for cleanup here because the rmtree
    function may be cleaned up before this object, so we use the atexit module
    instead.
    """

    def __new__(self):
        new = str.__new__(self, tempfile.mkdtemp())
        return new

    def __init__(self):
        self._path = self.__str__()
        atexit.register(self.cleanup)

    def cleanup(self):
        rmtree(self._path, ignore_errors=True)


# initialize config options
_init()


if hasattr(inspect, 'signature'):  # py35
    def _get_args(function, varargs=False):
        params = inspect.signature(function).parameters
        args = [key for key, param in params.items()
                if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)]
        if varargs:
            varargs = [param.name for param in params.values()
                       if param.kind == param.VAR_POSITIONAL]
            if len(varargs) == 0:
                varargs = None
            return args, varargs
        else:
            return args
else:
    def _get_args(function, varargs=False):
        out = inspect.getargspec(function)  # args, varargs, keywords, defaults
        if varargs:
            return out[:2]
        else:
            return out[0]