File: BatchOutputSelectionPanel.py

package info (click to toggle)
qgis 3.40.6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,181,336 kB
  • sloc: cpp: 1,593,302; python: 370,494; xml: 23,474; perl: 3,664; sh: 3,482; ansic: 2,257; sql: 2,133; yacc: 1,068; lex: 577; javascript: 540; lisp: 411; makefile: 157
file content (190 lines) | stat: -rw-r--r-- 8,024 bytes parent folder | download | duplicates (6)
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
"""
***************************************************************************
    BatchOutputSelectionPanel.py
    ---------------------
    Date                 : August 2012
    Copyright            : (C) 2012 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__ = "August 2012"
__copyright__ = "(C) 2012, Victor Olaya"

import os
import re

from qgis.core import (
    QgsMapLayer,
    QgsSettings,
    QgsProcessingParameterFolderDestination,
    QgsProcessingParameterRasterLayer,
    QgsProcessingParameterFeatureSource,
    QgsProcessingParameterVectorLayer,
    QgsProcessingParameterMultipleLayers,
    QgsProcessingParameterMapLayer,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterEnum,
    QgsProject,
    QgsProcessingParameterMatrix,
)
from qgis.PyQt.QtWidgets import (
    QWidget,
    QPushButton,
    QLineEdit,
    QHBoxLayout,
    QSizePolicy,
    QFileDialog,
)

from processing.gui.AutofillDialog import AutofillDialog


class BatchOutputSelectionPanel(QWidget):

    def __init__(self, output, alg, row, col, panel):
        super().__init__(None)
        self.alg = alg
        self.row = row
        self.col = col
        self.output = output
        self.panel = panel
        self.table = self.panel.tblParameters
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setMargin(0)
        self.text = QLineEdit()
        self.text.setText("")
        self.text.setMinimumWidth(300)
        self.text.setSizePolicy(
            QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
        )
        self.horizontalLayout.addWidget(self.text)
        self.pushButton = QPushButton()
        self.pushButton.setText("…")
        self.pushButton.clicked.connect(self.showSelectionDialog)
        self.horizontalLayout.addWidget(self.pushButton)
        self.setLayout(self.horizontalLayout)

    def showSelectionDialog(self):
        if isinstance(self.output, QgsProcessingParameterFolderDestination):
            self.selectDirectory()
            return

        filefilter = self.output.createFileFilter()
        settings = QgsSettings()
        if settings.contains("/Processing/LastBatchOutputPath"):
            path = str(settings.value("/Processing/LastBatchOutputPath"))
        else:
            path = ""
        filename, selectedFileFilter = QFileDialog.getSaveFileName(
            self, self.tr("Save File"), path, filefilter
        )
        if filename:
            if not filename.lower().endswith(
                tuple(re.findall("\\*(\\.[a-z]{1,10})", filefilter))
            ):
                ext = re.search("\\*(\\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    filename += ext.group(1)
            settings.setValue(
                "/Processing/LastBatchOutputPath", os.path.dirname(filename)
            )
            dlg = AutofillDialog(self.alg)
            dlg.exec()
            if dlg.mode is not None:
                if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL:
                    self.table.cellWidget(self.row, self.col).setValue(filename)
                elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS:
                    n = self.table.rowCount() - self.row
                    for i in range(n):
                        name = (
                            filename[: filename.rfind(".")]
                            + str(i + 1)
                            + filename[filename.rfind(".") :]
                        )
                        self.table.cellWidget(i + self.row, self.col).setValue(name)
                elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER:
                    for row in range(self.row, self.table.rowCount()):
                        v = self.panel.valueForParameter(row - 1, dlg.param_name)
                        param = self.alg.parameterDefinition(dlg.param_name)
                        if isinstance(
                            param,
                            (
                                QgsProcessingParameterRasterLayer,
                                QgsProcessingParameterFeatureSource,
                                QgsProcessingParameterVectorLayer,
                                QgsProcessingParameterMultipleLayers,
                                QgsProcessingParameterMapLayer,
                            ),
                        ):
                            if isinstance(v, QgsMapLayer):
                                s = v.name()
                            else:
                                if v in QgsProject.instance().mapLayers():
                                    layer = QgsProject.instance().mapLayer(v)
                                    # value is a layer ID, but we'd prefer to show a layer name if it's unique in the project
                                    if (
                                        len(
                                            [
                                                l
                                                for _, l in QgsProject.instance()
                                                .mapLayers()
                                                .items()
                                                if l.name().lower()
                                                == layer.name().lower()
                                            ]
                                        )
                                        == 1
                                    ):
                                        s = layer.name()
                                    else:
                                        # otherwise fall back to layer id
                                        s = v
                                else:
                                    # else try to use file base name
                                    # TODO: this is bad for database sources!!
                                    s = os.path.basename(v)
                                    s = os.path.splitext(s)[0]
                        elif isinstance(param, QgsProcessingParameterBoolean):
                            s = "true" if v else "false"
                        elif isinstance(param, QgsProcessingParameterEnum):
                            s = param.options()[v]
                        else:
                            s = str(v)
                        name = (
                            filename[: filename.rfind(".")]
                            + s
                            + filename[filename.rfind(".") :]
                        )
                        self.table.cellWidget(row, self.col).setValue(name)

    def selectDirectory(self):

        settings = QgsSettings()
        if settings.contains("/Processing/LastBatchOutputPath"):
            lastDir = str(settings.value("/Processing/LastBatchOutputPath"))
        else:
            lastDir = ""

        dirName = QFileDialog.getExistingDirectory(
            self, self.tr("Output Directory"), lastDir, QFileDialog.Option.ShowDirsOnly
        )

        if dirName:
            self.table.cellWidget(self.row, self.col).setValue(dirName)
            settings.setValue("/Processing/LastBatchOutputPath", dirName)

    def setValue(self, text):
        return self.text.setText(text)

    def getValue(self):
        return str(self.text.text())