1# -*- coding: utf-8 -*-
2# Copyright (C) 2012, Almar Klein
3#
4# Visvis is distributed under the terms of the (new) BSD License.
5# The full license can be found in 'license.txt'.
6
7""" Package visvis.functions
8
9Each module in this directory contains a function with the same
10name as the module it's in. These functions are automatically loaded
11in Visvis, thus making it very easy to expand Visvis' functionality.
12
13There are three things to take into account when making a new function:
14- The function to add should be the same name as the module in which
15  it is defined. Other helper functions or classes can be defined, but
16  these are not inserted in the Visvis namespace.
17- The function's docstring should be very descriptive and starting with
18  the function's signature. The docstring is also used to produce the
19  on-line documentation.
20
21
22"""
23
24import os
25import sys
26import zipfile
27
28from visvis.core.misc import splitPathInZip
29
30
31def _insertFunctions():
32    """ insert the function is this module's namespace.
33    """
34
35    # see which files we have
36    if hasattr(sys, '_MEIPASS'):  # PyInstaller
37        zipfilename, path = sys.executable, ""
38    else:
39        path = __file__
40        path = os.path.dirname( os.path.abspath(path) )
41        zipfilename, path = splitPathInZip(path)
42
43    if zipfilename:
44        # get list of files from zipfile
45        z = zipfile.ZipFile(zipfilename)
46        files = [os.path.split(i)[1] for i in z.namelist()
47                    if i.startswith('visvis') and i.count('functions')]
48    else:
49        # get list of files from file system
50        files = os.listdir(path)
51
52    # extract all functions
53    names = []
54    for file in files:
55        # not this file
56        if file.startswith('__'):
57            continue
58        # only python files
59        if file.endswith('.pyc'):
60            if file[:-1] in files:
61                continue # only try import once
62        elif not file.endswith('.py'):
63            continue
64        # build name
65        funname = os.path.splitext(file)[0]
66        # import module
67        mod = __import__("visvis.functions."+funname, fromlist=[funname])
68        if not hasattr(mod,funname):
69            print("module %s does not have a function with the same name!" % (
70                funname))
71        else:
72            # insert into THIS namespace
73            g = globals()
74            g[funname] = mod.__dict__[funname]
75            names.append(funname)
76
77    return names
78
79
80# do it and clean up
81_functionNames = _insertFunctions()
82