1# -*- coding: utf-8 -*-
2
3"""
4***************************************************************************
5    user.py
6    ---------------------
7    Date                 : January 2015
8    Copyright            : (C) 2015 by Nathan Woodrow
9    Email                : woodrow dot nathan at gmail dot com
10***************************************************************************
11*                                                                         *
12*   This program is free software; you can redistribute it and/or modify  *
13*   it under the terms of the GNU General Public License as published by  *
14*   the Free Software Foundation; either version 2 of the License, or     *
15*   (at your option) any later version.                                   *
16*                                                                         *
17***************************************************************************
18"""
19
20__author__ = 'Nathan Woodrow'
21__date__ = 'January 2015'
22__copyright__ = '(C) 2015, Nathan Woodrow'
23
24import os
25import sys
26import glob
27import traceback
28
29from qgis.PyQt.QtCore import QCoreApplication
30from qgis.core import Qgis, QgsApplication, QgsMessageLog
31
32
33def load_user_expressions(path):
34    """
35    Load all user expressions from the given paths
36    """
37    # Loop all py files and import them
38    modules = glob.glob(path + "/*.py")
39    names = [os.path.basename(f)[:-3] for f in modules]
40    for name in names:
41        if name == "__init__":
42            continue
43        # As user expression functions should be registered with qgsfunction
44        # just importing the file is enough to get it to load the functions into QGIS
45        try:
46            __import__("expressions.{0}".format(name), locals(), globals())
47        except:
48            error = traceback.format_exc()
49            msgtitle = QCoreApplication.translate("UserExpressions", "User expressions")
50            msg = QCoreApplication.translate("UserExpressions", "The user expression {0} is not valid").format(name)
51            QgsMessageLog.logMessage(msg + "\n" + error, msgtitle, Qgis.Warning)
52
53
54userpythonhome = os.path.join(QgsApplication.qgisSettingsDirPath(), "python")
55expressionspath = os.path.join(userpythonhome, "expressions")
56
57sys.path.append(userpythonhome)
58
59if not os.path.exists(expressionspath):
60    os.makedirs(expressionspath)
61
62initfile = os.path.join(expressionspath, "__init__.py")
63if not os.path.exists(initfile):
64    open(initfile, "w").close()
65
66template = """from qgis.core import *
67from qgis.gui import *
68
69@qgsfunction(args='auto', group='Custom', referenced_columns=[])
70def my_sum(value1, value2, feature, parent):
71    \"\"\"
72    Calculates the sum of the two parameters value1 and value2.
73    <h2>Example usage:</h2>
74    <ul>
75      <li>my_sum(5, 8) -> 13</li>
76      <li>my_sum(\"field1\", \"field2\") -> 42</li>
77    </ul>
78    \"\"\"
79    return value1 + value2
80"""
81
82default_expression_template = template
83
84try:
85    import expressions
86
87    expressions.load = load_user_expressions
88    expressions.load(expressionspath)
89    expressions.template = template
90except ImportError:
91    # We get a import error and crash for some reason even if we make the expressions package
92    # TODO Fix the crash on first load with no expressions folder
93    # But for now it's not the end of the world if it doesn't load the first time
94    pass
95