Esempio n. 1
0
def installLookupTable(key):
    """Attempts to install/save a previously registered lookup table into
    the ``[settingsbase]/luts`` directory.
    """

    # keyerror if not registered
    lut = _luts[key]
    destFile = op.join('luts', '{}.lut'.format(key))
    destFile = fslsettings.filePath(destFile)
    destDir = op.dirname(destFile)

    log.debug('Installing lookup table {} to {}'.format(key, destFile))

    if not op.exists(destDir):
        os.makedirs(destDir)

    lut.mapObj.save(destFile)

    # Update user-added settings
    lutNames = fslsettings.read('fsleyes.luts', OrderedDict())
    lutNames[key] = lut.name
    fslsettings.write('fsleyes.luts', lutNames)

    lut.mapFile = destFile
    lut.installed = True
Esempio n. 2
0
def test_initialise():

    # Assuming that initialise()
    # has not yet been called
    assert settings.read('nothing') is None
    assert settings.read('nothing', 'default') == 'default'
    settings.write('nothing', 'nothing')
    settings.delete('nothing')
    assert settings.readFile('nothing') is None
    settings.writeFile('nothing', 'nothing')
    settings.deleteFile('nothing')
    assert settings.filePath() is None
    assert settings.readAll() == {}
    assert settings.listFiles() == []
    settings.clear()

    with tests.testdir() as testdir:

        settings.initialise(cfgid='test', cfgdir=testdir, writeOnExit=False)

        assert settings.settings.configID == 'test'
        assert settings.settings.configDir == testdir

        settings.write('setting', 'value')

        assert settings.read('setting') == 'value'
        assert settings.read('nothing') is None
Esempio n. 3
0
def initialise():
    """Calls :func:`loadPlugin` on all plugin files in the FSLeyes settings
    directory, and found on the ``FSLEYES_PLUGIN_PATH`` environment variable.
    """
    pluginFiles = list(fslsettings.listFiles('plugins/*.py'))
    pluginFiles = [fslsettings.filePath(p) for p in pluginFiles]
    fpp = os.environ.get('FSLEYES_PLUGIN_PATH', None)

    if fpp is not None:
        for dirname in fpp.split(op.pathsep):
            pluginFiles.extend(glob.glob(op.join(dirname, '*.py')))

    for fname in pluginFiles:
        try:
            loadPlugin(fname)
        except Exception as e:
            log.warning('Failed to load plugin file %s: %s', fname, e)
Esempio n. 4
0
def installPlugin(filename):
    """Copies the given Python file into the FSLeyes settings directory,
    within a sub-directory called ``plugins``. After the file has been
    copied, the path to the copy is passed to :func:`loadPlugin`.
    """

    basename = op.splitext(op.basename(filename))[0]
    dest = 'plugins/{}.py'.format(basename)

    log.debug('Installing plugin %s', filename)

    with open(filename, 'rt')        as inf, \
         fslsettings.writeFile(dest) as outf:
        outf.write(inf.read())

    dest = fslsettings.filePath(dest)

    try:
        loadPlugin(dest)
    except Exception:
        fslsettings.deleteFile(dest)
        raise
Esempio n. 5
0
def init(force=False):
    """This function must be called before any of the other functions in this
    module can be used.

    It initialises the colour map and lookup table registers, loading all
    built-in and user-added colour map and lookup table files that exist.

    :arg force: Forces the registers to be re-initialised, even if they
                have already been initialised.
    """

    global _cmaps
    global _luts

    # Already initialised
    if not force and (_cmaps is not None) and (_luts is not None):
        return

    _cmaps = OrderedDict()
    _luts = OrderedDict()

    # Reads the order.txt file from the built-in
    # /colourmaps/ or /luts/ directory. This file
    # contains display names and defines the order
    # in which built-in maps should be displayed.
    def readOrderTxt(filename):
        maps = OrderedDict()

        if not op.exists(filename):
            return maps

        with open(filename, 'rt') as f:
            lines = f.read().split('\n')

            for line in lines:
                if line.strip() == '':
                    continue

                # The order.txt file is assumed to
                # contain one row per cmap/lut,
                # where the first word is the key
                # (the cmap/lut file name prefix),
                # and the remainder of the line is
                # the cmap/lut name
                key, name = line.split(' ', 1)
                maps[key.strip()] = name.strip()
        return maps

    # Reads any display names that have been
    # defined for user-added colourmaps/luts
    # (mapType is either 'cmap' or 'lut').
    def readDisplayNames(mapType):
        if mapType == 'cmap': key = 'fsleyes.colourmaps'
        elif mapType == 'lut': key = 'fsleyes.luts'
        return fslsettings.read(key, OrderedDict())

    # Get all colour map/lut IDs and
    # paths to the cmap/lut files. We
    # process cmaps/luts in the same
    # way, so we loop over all of
    # these lists, doing colour maps
    # first, then luts second.
    mapTypes = ['cmap', 'lut']
    builtinDirs = [getCmapDir(), getLutDir()]
    userDirs = ['colourmaps', 'luts']
    allBuiltins = [scanBuiltInCmaps(), scanBuiltInLuts()]
    allUsers = [scanUserAddedCmaps(), scanUserAddedLuts()]
    registers = [_cmaps, _luts]

    for mapType, builtinDir, userDir, builtinIDs, userIDs, register in zip(
            mapTypes, builtinDirs, userDirs, allBuiltins, allUsers, registers):

        builtinFiles = ['{}.{}'.format(m, mapType) for m in builtinIDs]
        builtinFiles = [_find(m, builtinDir) for m in builtinFiles]
        userFiles = ['{}.{}'.format(m, mapType) for m in userIDs]
        userFiles = [op.join(userDir, m) for m in userFiles]
        userFiles = [fslsettings.filePath(m) for m in userFiles]

        allIDs = builtinIDs + userIDs
        allFiles = builtinFiles + userFiles
        allFiles = {mid: mfile for mid, mfile in zip(allIDs, allFiles)}

        # Read order/display names from order.txt -
        # if an order.txt file exists in the user
        # dir, it takes precednece over built-in
        # order/display names.
        #
        # User-added display names may also be in
        # fslsettings. Any user-added maps with
        # the same ID as a builtin will override
        # the builtin.
        builtinOrder = op.join(builtinDir, 'order.txt')
        userOrder = op.join(userDir, 'order.txt')

        if op.exists(userOrder): names = readOrderTxt(userOrder)
        else: names = readOrderTxt(builtinOrder)

        names.update(readDisplayNames(mapType))

        # any maps which did not have a name
        # specified in order.txt (or, for
        # user-added maps, in fslsettings)
        # are added to the end of the list,
        # and their name is just set to the
        # ID (which is equal to the file name
        # prefix).
        for mid in allIDs:
            if mid not in names:
                names[mid] = mid

        # Now register all of those maps,
        # in the order defined by order.txt
        for mapID, mapName in names.items():

            # The user-added {id:name} dict
            # might contain obsolete/invalid
            # names, so we ignore keyerrors
            try:
                mapFile = allFiles[mapID]
            except KeyError:
                continue

            try:
                kwargs = {'key': mapID, 'name': mapName}

                if mapType == 'cmap': registerColourMap(mapFile, **kwargs)
                elif mapType == 'lut': registerLookupTable(mapFile, **kwargs)

                register[mapID].installed = True
                register[mapID].mapObj.saved = True

            except Exception as e:
                log.warn('Error processing custom {} '
                         'file {}: {}'.format(mapType, mapFile, str(e)),
                         exc_info=True)