/
chloe_algorithm_dialog.py
1095 lines (959 loc) · 46.9 KB
/
chloe_algorithm_dialog.py
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
***************************************************************************
chloe_algorithm_dialog.py
---------------------
Date : May 2015
Copyright : (C) 2015 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__ = 'Jean-Charles Naud/Alkante'
__date__ = 'May 2015'
__copyright__ = '(C) 2015, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from functools import partial
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtWidgets import (QWidget,
QVBoxLayout,
QPushButton,
QLabel,
QPlainTextEdit,
QLineEdit,
QComboBox,
QCheckBox,
QSizePolicy,
QDialogButtonBox,
QFileDialog,
QSpinBox)
from qgis.core import (QgsProcessingFeedback,
QgsProcessingParameterDefinition,
QgsSettings)
from qgis.gui import (QgsMessageBar,
QgsProjectionSelectionWidget,
QgsProcessingAlgorithmDialogBase)
from processing.gui.AlgorithmDialog import AlgorithmDialog
from processing.gui.AlgorithmDialogBase import AlgorithmDialogBase
from processing.gui.ParametersPanel import ParametersPanel
from processing.gui.MultipleInputPanel import MultipleInputPanel
from processing.gui.NumberInputPanel import NumberInputPanel
from processing.gui.DestinationSelectionPanel import DestinationSelectionPanel
from processing.gui.FileSelectionPanel import FileSelectionPanel
from processing.gui.wrappers import (WidgetWrapper,
EnumWidgetWrapper)
from processing.tools.dataobjects import createContext
from pprint import pformat
import time
from qgis.PyQt.QtCore import QCoreApplication, Qt
from qgis.PyQt.QtWidgets import QMessageBox, QPushButton, QSizePolicy, QDialogButtonBox
from qgis.PyQt.QtGui import QColor, QPalette
from qgis.core import (Qgis,
QgsProject,
QgsApplication,
QgsProcessingUtils,
QgsProcessingParameterDefinition,
QgsProcessingParameterFileDestination,
QgsProcessingParameterFolderDestination,
QgsProcessingAlgRunnerTask,
QgsProcessingOutputHtml,
QgsProcessingParameterVectorDestination,
QgsProcessingOutputLayerDefinition,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterRasterDestination,
QgsProcessingAlgorithm,
QgsProcessingParameterFile,
QgsTaskManager,
QgsMessageLog,)
from qgis.gui import (QgsGui,
QgsMessageBar,
QgsProcessingAlgorithmDialogBase)
from qgis.utils import iface
from processing.core.ProcessingLog import ProcessingLog
from processing.core.ProcessingConfig import ProcessingConfig
from processing.core.ProcessingResults import resultsList
from processing.gui.ParametersPanel import ParametersPanel
from processing.gui.BatchAlgorithmDialog import BatchAlgorithmDialog
from processing.gui.AlgorithmDialogBase import AlgorithmDialogBase
from processing.gui.AlgorithmExecutor import executeIterating, execute#, execute_in_place
from .ChloePostProcessing import ChloehandleAlgorithmResults
from processing.gui.wrappers import WidgetWrapper
from processing.tools import dataobjects
import os
import warnings
from functools import partial
from qgis.core import (QgsProcessingParameterDefinition,
QgsProcessingParameterExtent,
QgsProcessingParameterPoint,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterRasterDestination,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterVectorDestination,
QgsProject)
#from qgis.gui import (QgsProcessingContextGenerator,
#QgsProcessingParameterWidgetContext)
from qgis.utils import iface
from qgis.PyQt import uic
from qgis.PyQt.QtCore import QCoreApplication, Qt
from qgis.PyQt.QtWidgets import (QWidget, QHBoxLayout, QToolButton,
QLabel, QCheckBox, QSizePolicy)
from qgis.PyQt.QtGui import QIcon
from processing.gui.DestinationSelectionPanel import DestinationSelectionPanel
from processing.gui.wrappers import WidgetWrapperFactory, WidgetWrapper, RasterWidgetWrapper, FileWidgetWrapper
from processing.tools.dataobjects import createContext
from processing.gui.wrappers import WidgetWrapper, DIALOG_MODELER, DIALOG_BATCH, DIALOG_STANDARD
from .gui.csv_field_selection_panel import CSVFieldSelectionPanel
from .gui.values_selection_panel import ValuesSelectionPanel
from .gui.classification_table_panel import ClassificationTablePanel
from .gui.components.DialListCheckBox import DialListCheckBox
from .gui.table_replace_input_panel import TableReplaceInputPanel
from .gui.double_cmb_box_selection_panel import DoubleCmbBoxSelectionPanel
from .gui.list_selection_panel import ListSelectionPanel
from .gui.int_list_selection_panel import IntListSelectionPanel
from .gui.factor_table_panel import FactorTablePanel
from .gui.odd_even_number_spinbox import IntSpinbox
pluginPath = os.path.join(
QgsApplication.pkgDataPath(),
'python',
'plugins',
'processing')
class ChloeAlgorithmDialog(AlgorithmDialog):
def __init__(self, alg):
super().__init__(alg)
self.mainWidget().parametersHaveChanged()
def getParametersPanel(self, alg, parent):
return ChloeParametersPanel(parent, alg)
def accept(self):
#print("accept")
super().accept()
def finish(self, successful, result, context, feedback):
#print("finish...")
super().finish(successful, result, context, feedback)
keepOpen = not successful or ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN)
#print("keepOpen " + str(keepOpen) + "successFull " +str(successful) + str(ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN)))
if not keepOpen:
self.close()
else:
self.resetGui()
#
# def getParameterValues(self):
# """OVERLOAD"""
# QgsMessageLog.logMessage('getParameterValues','Processing', Qgis.Info)
#
# parameters = {}
#
# if self.mainWidget() is None:
# return parameters
#
# for param in self.algorithm().parameterDefinitions():
# if param.flags() & QgsProcessingParameterDefinition.FlagHidden:
# continue
# if not param.isDestination():
#
# if self.in_place and param.name() == 'INPUT':
# parameters[param.name()] = self.active_layer
# continue
#
# try:
# wrapper = self.mainWidget().wrappers[param.name()]
# except KeyError:
# continue
#
# # For compatibility with 3.x API, we need to check whether the wrapper is
# # the deprecated WidgetWrapper class. If not, it's the newer
# # QgsAbstractProcessingParameterWidgetWrapper class
# # TODO QGIS 4.0 - remove
# if issubclass(wrapper.__class__, WidgetWrapper):
# widget = wrapper.widget
# else:
# widget = wrapper.wrappedWidget()
#
# if widget is None:
# continue
#
# value = wrapper.parameterValue()
# parameters[param.name()] = value
#
# if not param.checkValueIsAcceptable(value):
# raise AlgorithmDialogBase.InvalidParameterValue(param, widget)
# else:
# if self.in_place and param.name() == 'OUTPUT':
# parameters[param.name()] = 'memory:'
# continue
#
# dest_project = None
# if not param.flags() & QgsProcessingParameterDefinition.FlagHidden and \
# isinstance(param, (QgsProcessingParameterRasterDestination,
# QgsProcessingParameterFeatureSink,
# QgsProcessingParameterVectorDestination,
# QgsProcessingParameterFileDestination)):
# if not isinstance(param, QgsProcessingParameterFileDestination):
# if self.mainWidget().checkBoxes[param.name()].isChecked():
# dest_project = QgsProject.instance()
# elif param.name() == 'OUTPUT_ASC':
#
# print('B : {}'.format(self.algorithm().output_asc_checked))
# print('obj : {}'.format(self.algorithm()))
# if self.mainWidget().checkBoxes[param.name()].isChecked():
# self.algorithm().output_asc_checked = True
# dest_project = QgsProject.instance()
# else:
# self.algorithm().output_asc_checked = False
# print('A : {}'.format(self.algorithm().output_asc_checked))
# value = self.mainWidget().outputWidgets[param.name()].getValue()
# if value and isinstance(value, QgsProcessingOutputLayerDefinition):
# value.destinationProject = dest_project
# elif value and isinstance(value, QgsProcessingParameterFileDestination) and param.name() == 'OUTPUT_ASC':
# value.destinationProject = dest_project
# if value:
# parameters[param.name()] = value
#
# return self.algorithm().preprocessParameters(parameters)
#
#
# def finish(self, successful, result, context, feedback):
# """Heavy overload"""
# feedback.pushInfo('finish')
# #QgsMessageLog.logMessage('finish','Processing', Qgis.Info)
# keepOpen = not successful or ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN)
# #self.setInfo('ICI :{}'.fromat(self.iterateParam)) # toto
# if self.iterateParam is None:
#
# # add html results to results dock
# for out in self.algorithm().outputDefinitions():
# if isinstance(out, QgsProcessingOutputHtml) and out.name() in result and result[out.name()]:
# resultsList.addResult(icon=self.algorithm().icon(), name=out.description(), timestamp=time.localtime(),
# result=result[out.name()])
#
# if not ChloehandleAlgorithmResults(self.algorithm(), context, feedback, not keepOpen):
# self.resetGui()
# return
#
# self.setExecuted(True)
# self.setResults(result)
# self.setInfo(self.tr('Algorithm \'{0}\' finished').format(self.algorithm().displayName()), escapeHtml=False)
#
# if not keepOpen:
# self.close()
# else:
# self.resetGui()
# if self.algorithm().hasHtmlOutputs():
# self.setInfo(
# self.tr('HTML output has been generated by this algorithm.'
# '\nOpen the results dialog to check it.'), escapeHtml=False)
#
def getParameterValues(self):
parameters = super().getParameterValues()
for param in self.algorithm().parameterDefinitions():
if isinstance(param,
(ChloeCSVParameterFileDestination,
ChloeASCParameterFileDestination,
ChloeParameterFolderDestination)):
paramName = param.name()
if paramName in parameters:
p = parameters[paramName]
#print("param " + str(p))
toBeOpened = self.mainWidget().checkBoxes[paramName].isChecked()
value = self.mainWidget().outputWidgets[paramName].getValue()
#print("value " + str(value))
newValue = { "data": value, "openLayer" : toBeOpened }
#print("newValue " + str(newValue))
parameters[paramName] = newValue
return self.algorithm().preprocessParameters(parameters)
class ChloeParametersPanel(ParametersPanel):
def __init__(self, parent, alg):
super().__init__(parent, alg)
w = QWidget()
layout = QVBoxLayout()
layout.setMargin(0)
layout.setSpacing(6)
label = QLabel()
label.setText(self.tr("Chloe Command line"))
layout.addWidget(label)
self.text = QPlainTextEdit()
self.text.setReadOnly(True)
layout.addWidget(self.text)
w.setLayout(layout)
self.layoutMain.addWidget(w)
self.connectParameterSignals()
self.parametersHaveChanged()
# def initWidgets(self):
# """Init widget panel for each input output"""
# super().initWidgets()
# for output_name, output_panel in self.outputWidgets.items():
#
# # Add check box for automacial load after process algorithm
# # for 'OUTPUT_ASC' (QgsProcessingParameterFileDestination)
# if output_name == 'OUTPUT_ASC':
# check = QCheckBox()
# check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file after running algorithm'))
#
# def skipOutputChanged(checkbox, skipped):
# checkbox.setEnabled(not skipped)
# if skipped:
# checkbox.setChecked(False)
# check.setChecked(not output_panel.outputIsSkipped())
# check.setEnabled(not output_panel.outputIsSkipped())
#
# output_panel.skipOutputChanged.connect(partial(skipOutputChanged, check))
# self.layoutMain.insertWidget(self.layoutMain.count() - 1, check)
# self.checkBoxes[output_name] = check
def initWidgets(self): # Heavy overload
# If there are advanced parameters — show corresponding groupbox
for param in self.alg.parameterDefinitions():
if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced:
self.grpAdvanced.show()
break
#widget_context = QgsProcessingParameterWidgetContext()
#if iface is not None:
# widget_context.setMapCanvas(iface.mapCanvas())
# Create widgets and put them in layouts
for param in self.alg.parameterDefinitions():
if param.flags() & QgsProcessingParameterDefinition.FlagHidden:
continue
print('initWidgets - param.name(): {}'.format(param.name()))
if param.isDestination(): # and param.name() != 'OUTPUT_ASC':
continue
else:
wrapper = WidgetWrapperFactory.create_wrapper(param, self.parent)
self.wrappers[param.name()] = wrapper
#widget = wrapper.widget
# For compatibility with 3.x API, we need to check whether the wrapper is
# the deprecated WidgetWrapper class. If not, it's the newer
# QgsAbstractProcessingParameterWidgetWrapper class
# TODO QGIS 4.0 - remove
is_python_wrapper = issubclass(wrapper.__class__, WidgetWrapper)
if not is_python_wrapper:
from qgis.gui import (QgsProcessingContextGenerator, QgsProcessingParameterWidgetContext)
widget_context = QgsProcessingParameterWidgetContext()
if iface is not None:
widget_context.setMapCanvas(iface.mapCanvas())
wrapper.setWidgetContext(widget_context)
widget = wrapper.createWrappedWidget(self.processing_context)
wrapper.registerProcessingContextGenerator(self.context_generator)
else:
widget = wrapper.widget
#if self.in_place and param.name() in ('INPUT', 'OUTPUT'):
# don't show the input/output parameter widgets in in-place mode
# we still need to CREATE them, because other wrappers may need to interact
# with them (e.g. those parameters which need the input layer for field
# selections/crs properties/etc)
# continue
if widget is not None:
if is_python_wrapper:
widget.setToolTip(param.toolTip())
if isinstance(param, QgsProcessingParameterFeatureSource):
layout = QHBoxLayout()
layout.setSpacing(6)
layout.setMargin(0)
layout.addWidget(widget)
button = QToolButton()
icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png'))
button.setIcon(icon)
button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
button.setToolTip(self.tr('Iterate over this layer, creating a separate output for every feature in the layer'))
button.setCheckable(True)
layout.addWidget(button)
layout.setAlignment(button, Qt.AlignTop)
self.iterateButtons[param.name()] = button
button.toggled.connect(self.buttonToggled)
widget = QWidget()
widget.setLayout(layout)
label = None
if not is_python_wrapper:
label = wrapper.createWrappedLabel()
else:
label = wrapper.label
if label is not None:
if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced:
self.layoutAdvanced.addWidget(label)
else:
self.layoutMain.insertWidget(
self.layoutMain.count() - 2, label)
elif is_python_wrapper:
desc = param.description()
if isinstance(param, QgsProcessingParameterExtent):
desc += self.tr(' (xmin, xmax, ymin, ymax)')
if isinstance(param, QgsProcessingParameterPoint):
desc += self.tr(' (x, y)')
if param.flags() & QgsProcessingParameterDefinition.FlagOptional:
desc += self.tr(' [optional]')
widget.setText(desc)
if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced:
self.layoutAdvanced.addWidget(widget)
else:
self.layoutMain.insertWidget(
self.layoutMain.count() - 2, widget)
for output in self.alg.destinationParameterDefinitions():
if output.flags() & QgsProcessingParameterDefinition.FlagHidden:
continue
#if self.in_place and param.name() in ('INPUT', 'OUTPUT'):
# continue
label = QLabel(output.description())
#print('initWidgets 2 - param.name(): {}'.format(param.name()))
widget = DestinationSelectionPanel(output, self.alg) # TODO, overload
self.layoutMain.insertWidget(self.layoutMain.count() - 1, label)
self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget)
if isinstance(output, (QgsProcessingParameterRasterDestination,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterVectorDestination
# alk: checkboxes for Chloe handling
,ChloeCSVParameterFileDestination,
ChloeASCParameterFileDestination,
ChloeParameterFolderDestination)
):
check = QCheckBox()
check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file(s) after running algorithm'))
def skipOutputChanged(checkbox, skipped):
checkbox.setEnabled(not skipped)
if skipped:
checkbox.setChecked(False)
check.setChecked(not widget.outputIsSkipped())
check.setEnabled(not widget.outputIsSkipped())
widget.skipOutputChanged.connect(partial(skipOutputChanged, check))
self.layoutMain.insertWidget(self.layoutMain.count() - 1, check)
self.checkBoxes[output.name()] = check
# initial state
if hasattr(output,'addToMapDefaultState'):
check.setChecked(output.addToMapDefaultState)
widget.setToolTip(param.toolTip())
self.outputWidgets[output.name()] = widget
for wrapper in list(self.wrappers.values()):
wrapper.postInitialize(list(self.wrappers.values()))
# # alk: checkboxes for Chloe handling
# for output in self.alg.destinationParameterDefinitions():
# if output.flags() & QgsProcessingParameterDefinition.FlagHidden:
# continue
# if isinstance(output, (ChloeCSVParameterFileDestination)) or isinstance(output, (ChloeASCParameterFileDestination)):
# check = QCheckBox()
# check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file(s) after running algorithm'))
# def skipOutputChanged(checkbox, skipped):
# checkbox.setEnabled(not skipped)
# if skipped:
# checkbox.setChecked(False)
# check.setChecked(not widget.outputIsSkipped())
# check.setEnabled(not widget.outputIsSkipped())
# widget.skipOutputChanged.connect(partial(skipOutputChanged, check))
# print(str(self.layoutMain)+1)
# self.layoutMain.insertWidget(self.layoutMain.count() - 1, check)
# self.checkBoxes[output.name()] = check
# # connecting alg outputLoading info with checkbox state
# self.alg.outputLoading[output.name()] = check.isChecked()
# def updateOutputLoadingState(alg, outputName, checkbox, state):
# self.alg.outputLoading[outputName] = checkbox.isChecked()
# print( outputName + " " + str(checkbox.isChecked()) + " " + str(self.alg.outputLoading) + " " + str(self.alg))
# #print(str(self.alg.parameters))
# check.stateChanged.connect(partial(updateOutputLoadingState, self, output.name(), check))
# alk: addition of wrapper special config handling
# for dependancy between wrapper, i.e. changing the value
# of a FileSelectionPanel entails the update of another widget
for k in self.wrappers:
w = self.wrappers[k]
if hasattr(w,'getParentWidgetConfig'):
print(str(w) + " " + "getParentWidgetConfig")
config = w.getParentWidgetConfig()
if config != None:
p = self.wrappers[config['paramName']]
m = getattr(w, config['refreshMethod'])
if m!=None:
print(str(p) + " " + str(p.widget))
# todo generalize valueChanged handling
# to any type of widget componant
if isinstance(p.widget, FileSelectionPanel):
p.widget.leText.textChanged.connect(m)
elif isinstance(p, RasterWidgetWrapper):
try:
p.combo.valueChanged.connect(m) # QGIS 3.8 version
except:
p.combo.currentIndexChanged.connect(m) # QGIS LTR 3.4
def connectParameterSignals(self):
for wrapper in list(self.wrappers.values()):
wrapper.widgetValueHasChanged.connect(self.parametersHaveChanged)
# TODO - remove when all wrappers correctly emit widgetValueHasChanged!
# For compatibility with 3.x API, we need to check whether the wrapper is
# the deprecated WidgetWrapper class. If not, it's the newer
# QgsAbstractProcessingParameterWidgetWrapper class
# TODO QGIS 4.0 - remove
if issubclass(wrapper.__class__, WidgetWrapper):
w = wrapper.widget
else:
w = wrapper.wrappedWidget()
self.connectWidgetChangedSignals(w)
for c in w.findChildren(QWidget):
self.connectWidgetChangedSignals(c)
for output_widget in self.outputWidgets.values():
self.connectWidgetChangedSignals(output_widget)
def connectWidgetChangedSignals(self, w):
if isinstance(w, QLineEdit):
w.textChanged.connect(self.parametersHaveChanged)
elif isinstance(w, QComboBox):
w.currentIndexChanged.connect(self.parametersHaveChanged)
elif isinstance(w, QgsProjectionSelectionWidget):
w.crsChanged.connect(self.parametersHaveChanged)
elif isinstance(w, QCheckBox):
w.stateChanged.connect(self.parametersHaveChanged)
elif isinstance(w, MultipleInputPanel):
w.selectionChanged.connect(self.parametersHaveChanged)
elif isinstance(w, NumberInputPanel):
w.hasChanged.connect(self.parametersHaveChanged)
elif isinstance(w, DestinationSelectionPanel):
w.destinationChanged.connect(self.parametersHaveChanged)
def parametersHaveChanged(self):
context = createContext()
feedback = QgsProcessingFeedback()
try:
parameters = self.parent.getParameterValues()
for output in self.alg.destinationParameterDefinitions():
if not output.name() in parameters or parameters[output.name()] is None:
parameters[output.name()] = self.tr("[temporary file]")
for p in self.alg.parameterDefinitions():
if (not p.name() in parameters and not p.flags() & QgsProcessingParameterDefinition.FlagOptional) \
or (not p.checkValueIsAcceptable(parameters[p.name()])):
# not ready yet
self.text.setPlainText('')
return
commands = self.alg.getConsoleCommands(parameters, context, feedback, executing=False)
commands = [c for c in commands if c not in ['cmd.exe', '/C ']]
self.text.setPlainText(" ".join(commands))
except AlgorithmDialogBase.InvalidParameterValue as e:
self.text.setPlainText(self.tr("Invalid value for parameter '{0}'").format(e.parameter.description()))
if e.parameter.name()=='MAP_CSV':
raise
class ChloeFieldsFromCSVWidgetWrapper(WidgetWrapper):
def createLabel(self):
"""Label create"""
if self.dialogType == DIALOG_STANDARD:
return None
else:
return super().createLabel()
def createWidget(self):
"""Widget creation to put like panel in dialog"""
if self.dialogType == DIALOG_STANDARD:
#return CSVFieldSelectionPanel(self.dialog, self.param.algorithm(), None)
return CSVFieldSelectionPanel(self.dialog, self.param.algorithm(), None)
elif self.dialogType == DIALOG_BATCH:
#todo
return None
else:
#todo
return CSVFieldSelectionPanel(self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
else:
return self.widget.getValue()
class ChloeValuesWidgetWrapper(WidgetWrapper):
def createLabel(self):
"""Label create"""
if self.dialogType == DIALOG_STANDARD:
return super().createLabel()
else:
return super().createLabel()
def createWidget(self):
"""Widget creation to put like panel in dialog"""
if self.dialogType == DIALOG_STANDARD:
return ValuesSelectionPanel(self.dialog, self.param.algorithm(), None)
elif self.dialogType == DIALOG_BATCH:
#todo
return None
else:
#todo
return ValuesSelectionPanel(self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
else:
return self.widget.getValue()
class ChloeClassificationTableWidgetWrapper(WidgetWrapper):
def createLabel(self):
"""Label create"""
if self.dialogType == DIALOG_STANDARD:
return None
else:
return super().createLabel()
def createWidget(self):
"""Widget creation to put like panel in dialog"""
if self.dialogType == DIALOG_STANDARD:
return ClassificationTablePanel(self.dialog, self.param.algorithm(), None)
elif self.dialogType == DIALOG_BATCH:
#todo
return None
else:
#todo
return ClassificationTablePanel(self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
else:
return self.widget.getValue()
class ChloeFactorTableWidgetWrapper(WidgetWrapper):
def createLabel(self):
"""Label create"""
if self.dialogType == DIALOG_STANDARD:
return None
else:
return super().createLabel()
def createWidget(self, input_matrix=None):
"""Widget creation to put like panel in dialog"""
if self.dialogType == DIALOG_STANDARD:
return FactorTablePanel(self.dialog, self.param.algorithm(), None, input_matrix)
elif self.dialogType == DIALOG_BATCH:
#todo
return None
else:
#todo
return FactorTablePanel(self.dialog, self.param.algorithm(), None, input_matrix)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
#else:
class ChloeMappingTableWidgetWrapper(WidgetWrapper):
def createLabel(self):
"""Label create"""
if self.dialogType == DIALOG_STANDARD:
return super().createLabel()
else:
return super().createLabel()
def createWidget(self, parentWidgetConfig=None):
"""Widget creation to put like panel in dialog"""
self.parentWidgetConfig = parentWidgetConfig
if self.dialogType == DIALOG_STANDARD:
return TableReplaceInputPanel(self.dialog, self.param.algorithm(), None)
elif self.dialogType == DIALOG_BATCH:
#todo
return None
else:
#todo
return (self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
else:
return self.widget.getValue()
def getParentWidgetConfig(self):
return self.parentWidgetConfig
def refreshMappingCombobox(self):
paramPanel = self.dialog.mainWidget()
wrapper = paramPanel.wrappers[self.parentWidgetConfig['paramName']]
widget = wrapper.widget
mappingFilepath = widget.getValue()
#print(str(mappingFilepath))
self.widget.updateMapCSV(mapFile=mappingFilepath)
class ChloeEnumUpdateStateWidgetWrapper(EnumWidgetWrapper):
def createWidget(self, dependantWidgetConfig=None):
""" """
self.dependantWidgetConfig = dependantWidgetConfig
res = super().createWidget()
return res
def postInitialize(self, widgetWrapperList):
self.widget.currentIndexChanged.connect(lambda x: self.updateDependantWidget(widgetWrapperList))
self.updateDependantWidget(widgetWrapperList)
def updateDependantWidget(self, wrapperList):
for c in self.dependantWidgetConfig:
dependantWrapperList = list(filter(lambda w: w.parameterDefinition().name()==c['paramName'], wrapperList))
if len(dependantWrapperList)>0:
dependantWrapper = dependantWrapperList[0]
if isinstance(dependantWrapper,FileWidgetWrapper):
dependantWidget = dependantWrapper.widget
else:
dependantWidget = dependantWrapper.wrappedWidget()
dependantWidget.setEnabled(self.value()==c['enableValue'])
class ChloeMultiEnumUpdateStateWidgetWrapper(EnumWidgetWrapper):
""" same as ChloeEnumUpdateStateWidgetWrapper class but we can use different value of the same parameter to unlock another parameter """
def createWidget(self, dependantWidgetConfig=None):
""" """
self.dependantWidgetConfig = dependantWidgetConfig
res = super().createWidget()
return res
def postInitialize(self, widgetWrapperList):
self.widget.currentIndexChanged.connect(lambda x: self.updateDependantWidget(widgetWrapperList))
self.updateDependantWidget(widgetWrapperList)
def updateDependantWidget(self, wrapperList):
for c in self.dependantWidgetConfig:
dependantWrapperList = list(filter(lambda w: w.parameterDefinition().name()==c['paramName'], wrapperList))
if len(dependantWrapperList)>0:
dependantWrapper = dependantWrapperList[0]
if isinstance(dependantWrapper,FileWidgetWrapper):
dependantWidget = dependantWrapper.widget
else:
dependantWidget = dependantWrapper.wrappedWidget()
dependantWidget.setEnabled(str(self.value()) in c['enableValue'].split(','))
class ChloeDoubleComboboxWidgetWrapper(WidgetWrapper):
def createLabel(self):
"""Label create"""
if self.dialogType == DIALOG_STANDARD:
return super().createLabel()
else:
return super().createLabel()
def createWidget(self, dictValues, initialValue, rasterLayerParamName, parentWidgetConfig=None):
"""Widget creation to put like panel in dialog"""
self.parentWidgetConfig = parentWidgetConfig
if self.dialogType == DIALOG_STANDARD:
return DoubleCmbBoxSelectionPanel(self.dialog, self.param.algorithm(), dictValues, initialValue, rasterLayerParamName)
elif self.dialogType == DIALOG_BATCH:
#todo
return None
else:
#todo
return (self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
else:
return self.widget.getValue()
def getParentWidgetConfig(self):
return self.parentWidgetConfig
def refreshMappingCombobox(self):
self.widget.initCalculateMetric()
self.widget.updateMetric()
class ChloeMultipleMetricsSelectorWidgetWrapper(WidgetWrapper):
def createWidget(self, dictValues, initialValue, rasterLayerParamName, parentWidgetConfig=None):
"""Widget creation to put like panel in dialog"""
self.parentWidgetConfig = parentWidgetConfig
if self.dialogType == DIALOG_STANDARD:
return ListSelectionPanel(self.dialog, self.param.algorithm(), dictValues, initialValue, rasterLayerParamName)
elif self.dialogType == DIALOG_BATCH:
#todo
return None
else:
#todo
return (self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
else:
return self.widget.getValue()
def getParentWidgetConfig(self):
return self.parentWidgetConfig
def refreshMetrics(self):
self.widget.update()
class ChloeAscRasterWidgetWrapper(RasterWidgetWrapper):
def createWidget(self, dependantWidgetConfig=None):
""" """
res = super().createWidget()
self.fileFilter = 'ASCII (*.asc)' + ';;' + self.tr('All files (*.*)')
return res
# overiding this method to redefine fileFilter
def getFileName(self, initial_value=''):
"""Shows a file open dialog"""
settings = QgsSettings()
if os.path.isdir(initial_value):
path = initial_value
elif os.path.isdir(os.path.dirname(initial_value)):
path = os.path.dirname(initial_value)
elif settings.contains('/Processing/LastInputPath'):
path = str(settings.value('/Processing/LastInputPath'))
else:
path = ''
filename, selected_filter = QFileDialog.getOpenFileName(self.widget, self.tr('Select File'),
path, self.fileFilter)
if filename:
settings.setValue('/Processing/LastInputPath',
os.path.dirname(str(filename)))
return filename, selected_filter
def postInitialize(self, widgetWrapperList):
# no initial selection
if self.dialogType == DIALOG_STANDARD:
self.combo.setLayer(None)
class ChloeIntListWidgetWrapper(WidgetWrapper):
def createWidget(self, initialValue, minValue, maxValue, oddNum):
"""Widget creation to put like panel in dialog"""
if self.dialogType == DIALOG_STANDARD:
return IntListSelectionPanel(self.dialog, self.param.algorithm(), initialValue, minValue, maxValue, oddNum)
elif self.dialogType == DIALOG_BATCH:
return None
else:
return (self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(str(value))
else:
# todo
self.widget.setValue(str(value))
def value(self):
"""Get value on the widget/component."""
if self.dialogType == DIALOG_STANDARD:
return self.widget.getValue()
else:
return self.widget.getValue()
class ChloeIntSpinboxWrapper(WidgetWrapper):
def createWidget(self, initialValue, minValue, maxValue, oddNum):
"""Widget creation to put like panel in dialog"""
if self.dialogType == DIALOG_STANDARD:
return IntSpinbox(self.dialog, self.param.algorithm(), initialValue, minValue, maxValue, oddNum)
elif self.dialogType == DIALOG_BATCH:
return None
else:
return (self.dialog, self.param.algorithm(), None)
def setValue(self, value):
"""Set value on the widget/component."""
if value is None:
return
if self.dialogType == DIALOG_STANDARD:
self.widget.setValue(int(value))
else:
# todo
self.widget.setValue(int(value))