File: ModelerParametersDialog.py

package info (click to toggle)
qgis 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: 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 (919 lines) | stat: -rw-r--r-- 36,978 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
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
# -*- coding: utf-8 -*-

"""
***************************************************************************
    ModelerParametersDialog.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'

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

__revision__ = '$Format:%H$'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtCore, QtGui, QtWebKit

from processing.core.WrongHelpFileException import WrongHelpFileException
from processing.gui.CrsSelectionPanel import CrsSelectionPanel
from processing.gui.MultipleInputPanel import MultipleInputPanel
from processing.gui.FixedTablePanel import FixedTablePanel
from processing.gui.RangePanel import RangePanel
from processing.modeler.ModelerAlgorithm import AlgorithmAndParameter
from processing.modeler.MultilineTextPanel import MultilineTextPanel
from processing.parameters.ParameterCrs import ParameterCrs
from processing.parameters.ParameterRaster import ParameterRaster
from processing.parameters.ParameterVector import ParameterVector
from processing.parameters.ParameterBoolean import ParameterBoolean
from processing.parameters.ParameterSelection import ParameterSelection
from processing.parameters.ParameterMultipleInput import ParameterMultipleInput
from processing.parameters.ParameterFixedTable import ParameterFixedTable
from processing.parameters.ParameterNumber import ParameterNumber
from processing.parameters.ParameterTableField import ParameterTableField
from processing.parameters.ParameterTable import ParameterTable
from processing.parameters.ParameterString import ParameterString
from processing.parameters.ParameterRange import ParameterRange
from processing.parameters.ParameterFile import ParameterFile
from processing.parameters.ParameterExtent import ParameterExtent
from processing.outputs.OutputRaster import OutputRaster
from processing.outputs.OutputVector import OutputVector
from processing.outputs.OutputTable import OutputTable
from processing.outputs.OutputExtent import OutputExtent
from processing.outputs.OutputString import OutputString
from processing.outputs.OutputNumber import OutputNumber
from processing.outputs.OutputHTML import OutputHTML
from processing.outputs.OutputFile import OutputFile
from processing.outputs.OutputDirectory import OutputDirectory


class ModelerParametersDialog(QtGui.QDialog):

    ENTER_NAME = '[Enter name if this is a final result]'
    NOT_SELECTED = '[Not selected]'
    USE_MIN_COVERING_EXTENT = '[Use min covering extent]'

    def __init__(self, alg, model, algIndex=None):
        QtGui.QDialog.__init__(self)
        self.setModal(True)
        self.alg = alg
        self.model = model
        self.algIndex = algIndex
        self.setupUi()
        self.params = None

    def setupUi(self):
        self.labels = {}
        self.widgets = {}
        self.checkBoxes = {}
        self.showAdvanced = False
        self.valueItems = {}
        self.dependentItems = {}
        self.resize(650, 450)
        self.buttonBox = QtGui.QDialogButtonBox()
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel
                | QtGui.QDialogButtonBox.Ok)
        tooltips = self.alg.getParameterDescriptions()
        self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Expanding)
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setSpacing(5)
        self.verticalLayout.setMargin(20)
        for param in self.alg.parameters:
            if param.isAdvanced:
                self.advancedButton = QtGui.QPushButton()
                self.advancedButton.setText('Show advanced parameters')
                self.advancedButton.setMaximumWidth(150)
                QtCore.QObject.connect(self.advancedButton,
                                       QtCore.SIGNAL('clicked()'),
                                       self.showAdvancedParametersClicked)
                self.verticalLayout.addWidget(self.advancedButton)
                break
        for param in self.alg.parameters:
            if param.hidden:
                continue
            desc = param.description
            if isinstance(param, ParameterExtent):
                desc += '(xmin, xmax, ymin, ymax)'
            label = QtGui.QLabel(desc)
            self.labels[param.name] = label
            widget = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = widget
            if param.name in tooltips.keys():
                tooltip = tooltips[param.name]
            else:
                tooltip = param.description
            label.setToolTip(tooltip)
            widget.setToolTip(tooltip)
            if param.isAdvanced:
                label.setVisible(self.showAdvanced)
                widget.setVisible(self.showAdvanced)
                self.widgets[param.name] = widget
            self.verticalLayout.addWidget(label)
            self.verticalLayout.addWidget(widget)

        for output in self.alg.outputs:
            if output.hidden:
                continue
            if isinstance(output, (OutputRaster, OutputVector, OutputTable,
                          OutputHTML, OutputFile, OutputDirectory)):
                label = QtGui.QLabel(output.description + '<'
                                     + output.__module__.split('.')[-1] + '>')
                item = QLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(item)
                self.valueItems[output.name] = item

        label = QtGui.QLabel(' ')
        self.verticalLayout.addWidget(label)
        label = QtGui.QLabel('Parent algorithms')
        self.dependenciesPanel = self.getDependenciesPanel()
        self.verticalLayout.addWidget(label)
        self.verticalLayout.addWidget(self.dependenciesPanel)

        self.verticalLayout.addStretch(1000)
        self.setLayout(self.verticalLayout)

        self.setPreviousValues()
        self.setWindowTitle(self.alg.name)
        self.verticalLayout2 = QtGui.QVBoxLayout()
        self.verticalLayout2.setSpacing(2)
        self.verticalLayout2.setMargin(0)
        self.tabWidget = QtGui.QTabWidget()
        self.tabWidget.setMinimumWidth(300)
        self.paramPanel = QtGui.QWidget()
        self.paramPanel.setLayout(self.verticalLayout)
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setWidget(self.paramPanel)
        self.scrollArea.setWidgetResizable(True)
        self.tabWidget.addTab(self.scrollArea, 'Parameters')
        self.webView = QtWebKit.QWebView()

        html = None
        url = None
        try:
            isText, help = self.alg.help()
            if help is not None:
                if isText:
                    html = help;
                else:
                    url = QtCore.QUrl(help)
            else:
                html = '<h2>Sorry, no help is available for this \
                        algorithm.</h2>'
        except WrongHelpFileException, e:
            html = e.args[0]
        try:
            if html:
                self.webView.setHtml(html)
            elif url:
                self.webView.load(url)
        except:
            self.webView.setHtml('<h2>Could not open help file :-( </h2>')
        self.tabWidget.addTab(self.webView, 'Help')
        self.verticalLayout2.addWidget(self.tabWidget)
        self.verticalLayout2.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout2)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL('accepted()'),
                               self.okPressed)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL('rejected()'),
                               self.cancelPressed)
        QtCore.QMetaObject.connectSlotsByName(self)

    def getAvailableDependencies(self):
        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)
        opts = []
        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                opts.append(str(i + 1) + ':' + alg.name)
            i += 1
        return opts

    def getDependenciesPanel(self):
        return MultipleInputPanel(self.getAvailableDependencies())

    def showAdvancedParametersClicked(self):
        self.showAdvanced = not self.showAdvanced
        if self.showAdvanced:
            self.advancedButton.setText('Hide advanced parameters')
        else:
            self.advancedButton.setText('Show advanced parameters')
        for param in self.alg.parameters:
            if param.isAdvanced:
                self.labels[param.name].setVisible(self.showAdvanced)
                self.widgets[param.name].setVisible(self.showAdvanced)

    def getRasterLayers(self):
        layers = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterRaster):
                layers.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))

        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)

        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                for out in alg.outputs:
                    if isinstance(out, OutputRaster):
                        layers.append(AlgorithmAndParameter(i, out.name,
                                      alg.name, out.description))
            i += 1

        return layers

    def getVectorLayers(self):
        layers = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterVector):
                layers.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))

        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)

        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                for out in alg.outputs:
                    if isinstance(out, OutputVector):
                        layers.append(AlgorithmAndParameter(i, out.name,
                                      alg.name, out.description))
            i += 1

        return layers

    def getTables(self):
        tables = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterTable):
                tables.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))

        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)

        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                for out in alg.outputs:
                    if isinstance(out, OutputTable):
                        tables.append(AlgorithmAndParameter(i, out.name,
                                      alg.name, out.description))
            i += 1

        return tables

    def getExtents(self):
        extents = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterExtent):
                extents.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))

        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)

        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                for out in alg.outputs:
                    if isinstance(out, OutputExtent):
                        extents.append(AlgorithmAndParameter(i, out.name,
                                       alg.name, out.description))
            i += 1

        return extents

    def getNumbers(self):
        numbers = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterNumber):
                numbers.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))

        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)

        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                for out in alg.outputs:
                    if isinstance(out, OutputNumber):
                        numbers.append(AlgorithmAndParameter(i, out.name,
                                       alg.name, out.description))
            i += 1
        return numbers

    def getFiles(self):
        files = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterFile):
                files.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))

        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)

        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                for out in alg.outputs:
                    if isinstance(out, OutputFile):
                        files.append(AlgorithmAndParameter(i, out.name,
                                     alg.name, out.description))
            i += 1
        return files

    def getBooleans(self):
        booleans = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterBoolean):
                booleans.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))
        return booleans

    def getStrings(self):
        strings = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterString):
                strings.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))

        if self.algIndex is None:
            dependent = []
        else:
            dependent = self.model.getDependentAlgorithms(self.algIndex)

        i = 0
        for alg in self.model.algs:
            if i not in dependent:
                for out in alg.outputs:
                    if isinstance(out, OutputString):
                        strings.append(AlgorithmAndParameter(i, out.name,
                                       alg.name, out.description))
            i += 1
        return strings

    def getTableFields(self):
        strings = []
        params = self.model.parameters
        for param in params:
            if isinstance(param, ParameterTableField):
                strings.append(AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM,
                        param.name, '', param.description))
        return strings

    def getWidgetFromParameter(self, param):
        if isinstance(param, ParameterRaster):
            item = QtGui.QComboBox()

            layers = self.getRasterLayers()
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(layer.name(), layer)
        elif isinstance(param, ParameterVector):
            item = QtGui.QComboBox()

            layers = self.getVectorLayers()
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(layer.name(), layer)
        elif isinstance(param, ParameterTable):
            item = QtGui.QComboBox()
            item.setEditable(True)
            layers = self.getTables()
            if param.optional:
                item.addItem(self.NOT_SELECTED, None)
            for layer in layers:
                item.addItem(layer.name(), layer)
        elif isinstance(param, ParameterBoolean):
            item = QtGui.QComboBox()
            item.addItem('Yes')
            item.addItem('No')
            bools = self.getBooleans()
            for b in bools:
                item.addItem(b.name(), b)
        elif isinstance(param, ParameterSelection):
            item = QtGui.QComboBox()
            item.addItems(param.options)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getVectorLayers()
            else:
                options = self.getRasterLayers()
            opts = []
            for opt in options:
                opts.append(opt.name())
            item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterString):
            strings = self.getStrings()
            if param.multiline:
                item = MultilineTextPanel(strings, self.model)
                item.setText(str(param.default))
            else:
                item = QtGui.QComboBox()
                item.setEditable(True)
                for s in strings:
                    item.addItem(s.name(), s)
                item.setEditText(str(param.default))
        elif isinstance(param, ParameterTableField):
            item = QtGui.QComboBox()
            item.setEditable(True)
            fields = self.getTableFields()
            for f in fields:
                item.addItem(f.name(), f)
        elif isinstance(param, ParameterNumber):
            item = QtGui.QComboBox()
            item.setEditable(True)
            numbers = self.getNumbers()
            for n in numbers:
                item.addItem(n.name(), n)
            item.setEditText(str(param.default))
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterExtent):
            item = QtGui.QComboBox()
            item.setEditable(True)
            extents = self.getExtents()
            if self.canUseAutoExtent():
                item.addItem(self.USE_MIN_COVERING_EXTENT, None)
            for ex in extents:
                item.addItem(ex.name(), ex)
            if not self.canUseAutoExtent():
                item.setEditText(str(param.default))
        elif isinstance(param, ParameterFile):
            item = QtGui.QComboBox()
            item.setEditable(True)
            files = self.getAvailableValuesOfType(ParameterFile, OutputFile)
            for f in files:
                item.addItem(f.name(), f)
        else:
            item = QtGui.QLineEdit()
            try:
                item.setText(str(param.default))
            except:
                pass
        return item

    def canUseAutoExtent(self):
        for param in self.alg.parameters:
            if isinstance(param, (ParameterRaster, ParameterVector)):
                return True
            if isinstance(param, ParameterMultipleInput):
                return True

    def setTableContent(self):
        params = self.alg.parameters
        outputs = self.alg.outputs
        numParams = 0
        for param in params:
            if not param.hidden:
                numParams += 1
        numOutputs = 0
        for output in outputs:
            if not output.hidden:
                numOutputs += 1
        self.tableWidget.setRowCount(numParams + numOutputs)

        i = 0
        for param in params:
            if not param.hidden:
                item = QtGui.QTableWidgetItem(param.description)
                item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.tableWidget.setItem(i, 0, item)
                item = self.getWidgetFromParameter(param)
                self.valueItems[param.name] = item
                self.tableWidget.setCellWidget(i, 1, item)
                self.tableWidget.setRowHeight(i, 22)
                i += 1

        for output in outputs:
            if not output.hidden:
                item = QtGui.QTableWidgetItem(output.description + '<'
                        + output.__module__.split('.')[-1] + '>')
                item.setFlags(QtCore.Qt.ItemIsEnabled)
                self.tableWidget.setItem(i, 0, item)
                item = QLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
                self.valueItems[output.name] = item
                self.tableWidget.setCellWidget(i, 1, item)
                self.tableWidget.setRowHeight(i, 22)
                i += 1

    def setComboBoxValue(self, combo, value, param):
        items = [combo.itemData(i) for i in range(combo.count())]
        idx = 0
        for item in items:
            if item and value:
                if item.alg == value.alg and item.param == value.param:
                    combo.setCurrentIndex(idx)
                    return
            idx += 1
        if combo.isEditable():
            value = self.model.getValueFromAlgorithmAndParameter(value)
            if value:
                combo.setEditText(str(value))
        elif isinstance(param, ParameterSelection):
            value = self.model.getValueFromAlgorithmAndParameter(value)
            combo.setCurrentIndex(int(value))
        elif isinstance(param, ParameterBoolean):
            value = self.model.getValueFromAlgorithmAndParameter(value) \
                    == str(True)
            if value:
                combo.setCurrentIndex(0)
            else:
                combo.setCurrentIndex(1)

    def setPreviousValues(self):
        if self.algIndex is not None:
            for (name, value) in \
                    self.model.algParameters[self.algIndex].items():
                widget = self.valueItems[name]
                param = self.alg.getParameterFromName(name)
                if isinstance(param, (
                        ParameterRaster,
                        ParameterVector,
                        ParameterTable,
                        ParameterTableField,
                        ParameterSelection,
                        ParameterNumber,
                        ParameterBoolean,
                        ParameterExtent,
                        )):
                    self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterString):
                    if param.multiline:
                        widget.setValue(value)
                    else:
                        self.setComboBoxValue(widget, value, param)
                elif isinstance(param, ParameterCrs):
                    value = self.model.getValueFromAlgorithmAndParameter(value)
                    widget.setAuthid(value)
                elif isinstance(param, ParameterFixedTable):
                    pass
                elif isinstance(param, ParameterMultipleInput):
                    value = self.model.getValueFromAlgorithmAndParameter(value)
                    values = value.split(';')
                    selectedoptions = []
                    if param.datatype \
                            == ParameterMultipleInput.TYPE_VECTOR_ANY:
                        options = self.getVectorLayers()
                    else:
                        options = self.getRasterLayers()
                    for i in range(len(options)):
                        option = options[i]
                        for aap in values:
                            if str(option) == aap:
                                selectedoptions.append(i)
                    widget.setSelectedItems(selectedoptions)
                else:
                    pass

            for out in self.alg.outputs:
                if not out.hidden:
                    value = self.model.algOutputs[self.algIndex][out.name]
                    if value is not None:
                        widget = \
                            self.valueItems[out.name].setText(unicode(value))

            selected = []
            dependencies = self.getAvailableDependencies()
            index = -1
            for dependency in dependencies:
                index += 1
                n = int(dependency[:dependency.find(':')]) - 1
                if n in self.model.dependencies[self.algIndex]:
                    selected.append(index)

            self.dependenciesPanel.setSelectedItems(selected)

    def setParamValues(self):
        self.params = {}
        self.values = {}
        self.outputs = {}

        params = self.alg.parameters
        outputs = self.alg.outputs

        for param in params:
            if param.hidden:
                continue
            if not self.setParamValue(param, self.valueItems[param.name]):
                return False
        for output in outputs:
            if output.hidden:
                self.outputs[output.name] = None
            else:
                name = unicode(self.valueItems[output.name].text())
                if name.strip() != '' and name \
                        != ModelerParametersDialog.ENTER_NAME:
                    self.outputs[output.name] = name
                else:
                    self.outputs[output.name] = None

        selectedOptions = self.dependenciesPanel.selectedoptions

        # This index are based on the list of available dependencies.
        # we translate them into indices based on the whole set of
        # algorithm in the model. We just take the values in the
        # beginning of the string representing the algorithm.
        availableDependencies = self.getAvailableDependencies()
        self.dependencies = []
        for selected in selectedOptions:
            s = availableDependencies[selected]
            n = int(s[:s.find(':')]) - 1
            self.dependencies.append(n)

        return True

    def setParamValueLayerOrTable(self, param, widget):
        idx = widget.currentIndex()
        if idx < 0:
            return False
        else:
            value = widget.itemData(widget.currentIndex())
            self.params[param.name] = value
            return True

    def setParamBooleanValue(self, param, widget):
        if widget.currentIndex() < 2:
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            self.values[name] = str(widget.currentIndex() == 0)
        else:
            value = widget.itemData(widget.currentIndex())
            self.params[param.name] = value
        return True

    def setParamTableFieldValue(self, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            s = str(widget.currentText()).strip()
            if s == '':
                if param.optional:
                    self.params[param.name] = None
                    return True
                else:
                    return False
            else:
                self.params[param.name] = value
                self.values[name] = str(widget.currentText())
                return True
        else:
            value = widget.itemData(widget.currentIndex())
            self.params[param.name] = value
        return True

    def setParamStringValue(self, param, widget):
        if param.multiline:
            name = self.getSafeNameForHarcodedParameter(param)
            paramValue = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            value = widget.getValue()
            option = widget.getOption()
            if option == MultilineTextPanel.USE_TEXT:
                if value == '':
                    if param.optional:
                        self.params[param.name] = None
                        return True
                    else:
                        return False
                else:
                    self.values[name] = value

                    self.params[param.name] = paramValue
            else:
                self.params[param.name] = value
        else:
            #if widget.currentText() == '':
            #    return False
            idx = widget.findText(widget.currentText())
            if idx < 0:
                name = self.getSafeNameForHarcodedParameter(param)
                value = AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
                self.params[param.name] = value
                value = str(widget.currentText()).strip()
                if value == '':
                    if param.optional:
                        self.values[name] = None
                        return True
                    else:
                        return False
                else:
                    self.values[name] = str(widget.currentText())
            else:
                value = widget.itemData(widget.currentIndex())
                self.params[param.name] = value
        return True

    def setParamFileValue(self, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            s = str(widget.currentText())
            self.values[name] = s
        else:
            value = widget.itemData(widget.currentIndex())
            self.params[param.name] = value
        return True

    def setParamNumberValue(self, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            s = str(widget.currentText())
            try:
                float(s)
                self.values[name] = s
            except:
                return False
        else:
            value = widget.itemData(widget.currentIndex())
            self.params[param.name] = value
        return True

    def setParamExtentValue(self, param, widget):
        idx = widget.findText(widget.currentText())
        if idx < 0:
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            s = str(widget.currentText())
            try:
                tokens = s.split(',')
                if len(tokens) != 4:
                    return False
                for token in tokens:
                    float(token)
            except:
                return False
            self.values[name] = s
        else:
            value = widget.itemData(widget.currentIndex())
            self.params[param.name] = value
        return True

    def setParamValue(self, param, widget):
        if isinstance(param, (ParameterRaster, ParameterVector,
                      ParameterTable)):
            return self.setParamValueLayerOrTable(param, widget)
        elif isinstance(param, ParameterBoolean):
            return self.setParamBooleanValue(param, widget)
        elif isinstance(param, ParameterString):
            return self.setParamStringValue(param, widget)
        elif isinstance(param, ParameterNumber):
            return self.setParamNumberValue(param, widget)
        elif isinstance(param, ParameterExtent):
            return self.setParamExtentValue(param, widget)
        elif isinstance(param, ParameterFile):
            return self.setParamFileValue(param, widget)
        elif isinstance(param, ParameterSelection):
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            self.values[name] = str(widget.currentIndex())
            return True
        elif isinstance(param, ParameterRange):
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            self.values[name] = str(widget.getValue())
            return True
        elif isinstance(param, ParameterCrs):
            authid = widget.getValue()
            if authid is None:
                self.params[param.name] = None
            else:
                name = self.getSafeNameForHarcodedParameter(param)
                value = AlgorithmAndParameter(
                        AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
                self.params[param.name] = value
                self.values[name] = authid
            return True
        elif isinstance(param, ParameterFixedTable):
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            self.values[name] = ParameterFixedTable.tableToString(widget.table)
            return True
        elif isinstance(param, ParameterTableField):
            return self.setParamTableFieldValue(param, widget)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = self.getVectorLayers()
            else:
                options = self.getRasterLayers()
            values = []
            for index in widget.selectedoptions:
                values.append(options[index].serialize())
            if len(values) == 0 and not param.optional:
                return False
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            self.values[name] = ';'.join(values)
            return True
        else:
            name = self.getSafeNameForHarcodedParameter(param)
            value = AlgorithmAndParameter(
                    AlgorithmAndParameter.PARENT_MODEL_ALGORITHM, name)
            self.params[param.name] = value
            self.values[name] = unicode(widget.text())
            return True

    def getSafeNameForHarcodedParameter(self, param):
        if self.algIndex is None:
            return 'HARDCODEDPARAMVALUE_' + param.name + '_' \
                + str(len(self.model.algs))
        else:
            return 'HARDCODEDPARAMVALUE_' + param.name + '_' \
                + str(self.algIndex)

    def okPressed(self):
        if self.setParamValues():
            self.close()
        else:
            QMessageBox.critical(self, 'Unable to add algorithm',
                                 'Wrong or missing parameter values')
            self.params = None

    def cancelPressed(self):
        self.params = None
        self.close()