File: SaveAsPythonScriptAction.py

package info (click to toggle)
qgis 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 374,696 kB
  • ctags: 66,263
  • sloc: cpp: 396,139; ansic: 241,070; python: 130,609; xml: 14,884; perl: 1,290; sh: 1,287; sql: 500; yacc: 268; lex: 242; makefile: 168
file content (126 lines) | stat: -rw-r--r-- 5,325 bytes parent folder | download
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
# -*- coding: utf-8 -*-

"""
***************************************************************************
    SaveAsPythonScriptAction.py
    ---------------------
    Date                 : April 2013
    Copyright            : (C) 2013 by Victor Olaya
    Email                : volayaf at gmail dot com
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'April 2013'
__copyright__ = '(C) 2013, Victor Olaya'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from processing.gui.ContextAction import ContextAction
from processing.modeler.ModelerAlgorithm import ModelerAlgorithm, \
    AlgorithmAndParameter
from processing.script.ScriptUtils import ScriptUtils
from processing.parameters.ParameterMultipleInput import ParameterMultipleInput

class SaveAsPythonScriptAction(ContextAction):

    def __init__(self):
        self.name = 'Save as Python script'

    def isEnabled(self):
        return isinstance(self.alg, ModelerAlgorithm)

    def execute(self):
        filename = str(QFileDialog.getSaveFileName(None, 'Save Script',
                       ScriptUtils.scriptsFolder(), 'Python scripts (*.py)'))

        if filename:
            if not filename.endswith('.py'):
                filename += '.py'
            text = self.translateToPythonCode(self.alg)
            try:
                fout = open(filename, 'w')
                fout.write(text)
                fout.close()
                if filename.replace('\\', '/').startswith(
                        ScriptUtils.scriptsFolder().replace('\\', '/')):
                    self.toolbox.updateProvider('script')
            except:
                QMessageBox.warning(self, self.tr('I/O error'),
                        self.tr('Unable to save edits. Reason:\n %s')
                        % unicode(sys.exc_info()[1]))

    def translateToPythonCode(self, model):
        s = ['##' + model.name + '=name']
        for param in model.parameters:
            s.append(str(param.getAsScriptCode().lower()))
        i = 0
        for outs in model.algOutputs:
            for out in outs.keys():
                if outs[out]:
                    s.append('##' + out.lower() + '_alg' + str(i) + '='
                             + model.getOutputType(i, out))
            i += 1
        i = 0
        iMultiple = 0
        for alg in model.algs:
            multiple = []
            runline = 'outputs_' + str(i) + '=processing.runalg("' \
                + alg.commandLineName() + '"'
            for param in alg.parameters:
                aap = model.algParameters[i][param.name]
                if aap is None:
                    runline += ', None'
                elif isinstance(param, ParameterMultipleInput):
                    value = model.paramValues[aap.param]
                    tokens = value.split(';')
                    layerslist = []
                    for token in tokens:
                        (iAlg, paramname) = token.split('|')
                        if float(iAlg) == float(
                                AlgorithmAndParameter.PARENT_MODEL_ALGORITHM):
                            if model.ismodelparam(paramname):
                                value = paramname.lower()
                            else:
                                value = model.paramValues[paramname]
                        else:
                            value = 'outputs_' + str(iAlg) + "['" + paramname \
                                + "']"
                        layerslist.append(str(value))

                    multiple.append('multiple_' + str(iMultiple) + '=['
                                    + ','.join(layerslist) + ']')
                    runline += ', ";".join(multiple_' + str(iMultiple) + ') '
                else:
                    if float(aap.alg) == float(
                            AlgorithmAndParameter.PARENT_MODEL_ALGORITHM):
                        if model.ismodelparam(aap.param):
                            runline += ', ' + aap.param.lower()
                        else:
                            runline += ', ' + str(model.paramValues[aap.param])
                    else:
                        runline += ', outputs_' + str(aap.alg) + "['" \
                            + aap.param + "']"
            for out in alg.outputs:
                value = model.algOutputs[i][out.name]
                if value:
                    name = out.name.lower() + '_alg' + str(i)
                else:
                    name = str(None)
                runline += ', ' + name
            i += 1
            s += multiple
            s.append(str(runline + ')'))
        return '\n'.join(s)