-
Notifications
You must be signed in to change notification settings - Fork 967
/
basic.py
2556 lines (2267 loc) · 110 KB
/
basic.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
"""
Basic tool parameters.
"""
import logging
import re
import os
import os.path
from xml.etree.ElementTree import XML
from galaxy import util
from galaxy.web import form_builder
from galaxy.util import string_as_bool, sanitize_param, unicodify
from galaxy.util import listify
from galaxy.util.odict import odict
from galaxy.util.expressions import ExpressionContext
from sanitize import ToolParameterSanitizer
import validation
import galaxy.tools.parser
from ..parser import get_input_source as ensure_input_source
from ..parameters import history_query
from ..parameters import dynamic_options
from .dataset_matcher import DatasetMatcher
from .dataset_matcher import DatasetCollectionMatcher
# For BaseURLToolParameter
from galaxy.web import url_for
from galaxy.util.dictifiable import Dictifiable
import galaxy.model
log = logging.getLogger(__name__)
WORKFLOW_PARAMETER_REGULAR_EXPRESSION = re.compile( '''\$\{.+?\}''' )
def contains_workflow_parameter(value, search=False):
if not isinstance( value, basestring ):
return False
if search and WORKFLOW_PARAMETER_REGULAR_EXPRESSION.search(value):
return True
if not search and WORKFLOW_PARAMETER_REGULAR_EXPRESSION.match(value):
return True
return False
class ToolParameter( object, Dictifiable ):
"""
Describes a parameter accepted by a tool. This is just a simple stub at the
moment but in the future should encapsulate more complex parameters (lists
of valid choices, validation logic, ...)
"""
dict_collection_visible_keys = ( 'name', 'argument', 'type', 'label', 'help' )
def __init__( self, tool, input_source, context=None ):
input_source = ensure_input_source(input_source)
self.tool = tool
self.refresh_on_change = False
self.refresh_on_change_values = []
self.argument = input_source.get("argument")
self.name = ToolParameter.parse_name( input_source )
self.type = input_source.get("type")
self.hidden = input_source.get("hidden", False)
self.is_dynamic = False
self.label = input_source.parse_label()
self.help = input_source.parse_help()
sanitizer_elem = input_source.parse_sanitizer_elem()
if sanitizer_elem is not None:
self.sanitizer = ToolParameterSanitizer.from_element( sanitizer_elem )
else:
self.sanitizer = None
self.html = "no html set"
try:
# These don't do anything right? These we should
# delete these two lines and eliminate checks for
# self.repeat in this file. -John
self.repeat = input_source.elem().get("repeat", None)
self.condition = input_source.elem().get( "condition", None )
except Exception:
self.repeat = None
# Optional DataToolParameters are used in tools like GMAJ and LAJ
self.optional = input_source.parse_optional()
self.validators = []
for elem in input_source.parse_validator_elems():
self.validators.append( validation.Validator.from_element( self, elem ) )
@property
def visible( self ):
"""Return true if the parameter should be rendered on the form"""
return True
def get_label( self ):
"""Return user friendly name for the parameter"""
if self.label:
return self.label
else:
return self.name
def get_html_field( self, trans=None, value=None, other_values={} ):
raise TypeError( "Abstract Method" )
def get_html( self, trans=None, value=None, other_values={} ):
"""
Returns the html widget corresponding to the parameter.
Optionally attempt to retain the current value specific by 'value'
"""
return self.get_html_field( trans, value, other_values ).get_html()
def from_html( self, value, trans=None, other_values={} ):
"""
Convert a value from an HTML POST into the parameters preferred value
format.
"""
return value
def from_json( self, value, trans=None, other_values={} ):
return self.from_html( value, trans, other_values )
def get_initial_value( self, trans, other_values ):
"""
Return the starting value of the parameter
"""
return None
def get_initial_value_from_history_prevent_repeats( self, trans, other_values, already_used ):
"""
Get the starting value for the parameter, but if fetching from the history, try
to find a value that has not yet been used. already_used is a list of objects that
tools must manipulate (by adding to it) to store a memento that they can use to detect
if a value has already been chosen from the history. This is to support the capability to
choose each dataset once
"""
return self.get_initial_value( trans, other_values )
def get_required_enctype( self ):
"""
If this parameter needs the form to have a specific encoding
return it, otherwise return None (indicating compatibility with
any encoding)
"""
return None
def get_dependencies( self ):
"""
Return the names of any other parameters this parameter depends on
"""
return []
def to_string( self, value, app ):
"""Convert a value to a string representation suitable for persisting"""
if not isinstance( value, basestring ):
value = str( value )
return unicodify( value )
def to_python( self, value, app ):
"""Convert a value created with to_string back to an object representation"""
return value
def value_to_basic( self, value, app ):
if isinstance( value, RuntimeValue ):
return { '__class__': 'RuntimeValue' }
elif isinstance( value, dict ):
if value.get('__class__') == 'RuntimeValue':
return value
return self.to_string( value, app )
def value_from_basic( self, value, app, ignore_errors=False ):
# HACK: Some things don't deal with unicode well, psycopg problem?
if type( value ) == unicode:
value = str( value )
# Handle Runtime values (valid for any parameter?)
if isinstance( value, dict ) and '__class__' in value and value['__class__'] == "RuntimeValue":
return RuntimeValue()
# Delegate to the 'to_python' method
if ignore_errors:
try:
return self.to_python( value, app )
except:
return value
else:
return self.to_python( value, app )
def value_to_display_text( self, value, app ):
"""
Convert a value to a text representation suitable for displaying to
the user
"""
return unicodify( value )
def to_param_dict_string( self, value, other_values={} ):
"""Called via __str__ when used in the Cheetah template"""
if value is None:
value = ""
elif not isinstance( value, basestring ):
value = str( value )
if self.tool is None or self.tool.options.sanitize:
if self.sanitizer:
value = self.sanitizer.sanitize_param( value )
else:
value = sanitize_param( value )
return value
def validate( self, value, trans=None ):
if value == "" and self.optional:
return
for validator in self.validators:
validator.validate( value, trans )
def to_dict( self, trans, view='collection', value_mapper=None, other_values={} ):
""" to_dict tool parameter. This can be overridden by subclasses. """
tool_dict = super( ToolParameter, self ).to_dict()
tool_dict[ 'model_class' ] = self.__class__.__name__
tool_dict[ 'optional' ] = self.optional
tool_dict[ 'hidden' ] = self.hidden
tool_dict[ 'is_dynamic' ] = self.is_dynamic
if hasattr( self, 'value' ):
tool_dict[ 'value' ] = self.value
return tool_dict
@classmethod
def build( cls, tool, param ):
"""Factory method to create parameter of correct type"""
param_name = cls.parse_name( param )
param_type = param.get("type")
if not param_type:
raise ValueError( "Tool parameter '%s' requires a 'type'" % ( param_name ) )
elif param_type not in parameter_types:
raise ValueError( "Tool parameter '%s' uses an unknown type '%s'" % ( param_name, param_type ) )
else:
return parameter_types[param_type]( tool, param )
@classmethod
def parse_name(cls, input_source):
name = input_source.get("name", None)
if name is None:
argument = input_source.get("argument")
if argument:
name = argument.lstrip("-")
else:
raise ValueError("Tool parameter must specify a name.")
return name
class TextToolParameter( ToolParameter ):
"""
Parameter that can take on any text value.
>>> p = TextToolParameter( None, XML( '<param name="blah" type="text" size="4" value="default" />' ) )
>>> print p.name
blah
>>> print p.get_html()
<input type="text" name="blah" size="4" value="default">
>>> print p.get_html( value="meh" )
<input type="text" name="blah" size="4" value="meh">
"""
def __init__( self, tool, input_source ):
input_source = ensure_input_source(input_source)
ToolParameter.__init__( self, tool, input_source )
self.size = input_source.get( 'size' )
self.value = input_source.get( 'value' )
self.area = input_source.get_bool( 'area', False )
def get_html_field( self, trans=None, value=None, other_values={} ):
if value is None:
value = self.value
if self.area:
return form_builder.TextArea( self.name, self.size, value )
else:
return form_builder.TextField( self.name, self.size, value )
def to_string( self, value, app ):
"""Convert a value to a string representation suitable for persisting"""
if value is None:
rval = ''
else:
rval = util.smart_str( value )
return rval
def validate( self, value, trans=None ):
search = self.type == "text"
if not ( trans and trans.workflow_building_mode and contains_workflow_parameter(value, search=search) ):
return super( TextToolParameter, self ).validate( value, trans )
def get_initial_value( self, trans, other_values ):
return self.value
def to_dict( self, trans, view='collection', value_mapper=None, other_values={} ):
d = super(TextToolParameter, self).to_dict(trans)
d['area'] = self.area
d['size'] = self.size
return d
class IntegerToolParameter( TextToolParameter ):
"""
Parameter that takes an integer value.
>>> from galaxy.util.bunch import Bunch
>>> trans = Bunch( history=Bunch(), workflow_building_mode=True )
>>> p = IntegerToolParameter( None, XML( '<param name="blah" type="integer" size="4" value="10" />' ) )
>>> print p.name
blah
>>> print p.get_html()
<input type="text" name="blah" size="4" value="10">
>>> type( p.from_html( "10", trans ) )
<type 'int'>
>>> type( p.from_html( "bleh", trans ) )
Traceback (most recent call last):
...
ValueError: An integer or workflow parameter e.g. ${name} is required
"""
dict_collection_visible_keys = ToolParameter.dict_collection_visible_keys + ( 'min', 'max' )
def __init__( self, tool, input_source ):
input_source = ensure_input_source(input_source)
TextToolParameter.__init__( self, tool, input_source )
if self.value:
try:
int( self.value )
except:
raise ValueError( "An integer is required" )
elif self.value is None and not self.optional:
raise ValueError( "The settings for the field named '%s' require a 'value' setting and optionally a default value which must be an integer" % self.name )
self.min = input_source.get( 'min' )
self.max = input_source.get( 'max' )
if self.min:
try:
self.min = int( self.min )
except:
raise ValueError( "An integer is required" )
if self.max:
try:
self.max = int( self.max )
except:
raise ValueError( "An integer is required" )
if self.min is not None or self.max is not None:
self.validators.append( validation.InRangeValidator( None, self.min, self.max ) )
def get_html_field( self, trans=None, value=None, other_values={} ):
if isinstance( value, int ):
value = str( value )
return super( IntegerToolParameter, self ).get_html_field( trans=trans, value=value, other_values=other_values )
def from_html( self, value, trans, other_values={} ):
try:
return int( value )
except:
if contains_workflow_parameter( value ) and trans.workflow_building_mode:
return value
if not value and self.optional:
return ""
if trans.workflow_building_mode:
raise ValueError( "An integer or workflow parameter e.g. ${name} is required" )
else:
raise ValueError( "An integer is required" )
def to_python( self, value, app ):
try:
return int( value )
except Exception, err:
if contains_workflow_parameter(value):
return value
if not value and self.optional:
return None
raise err
def get_initial_value( self, trans, other_values ):
if self.value:
return int( self.value )
else:
return None
class FloatToolParameter( TextToolParameter ):
"""
Parameter that takes a real number value.
>>> from galaxy.util.bunch import Bunch
>>> trans = Bunch( history=Bunch(), workflow_building_mode=True )
>>> p = FloatToolParameter( None, XML( '<param name="blah" type="float" size="4" value="3.141592" />' ) )
>>> print p.name
blah
>>> print p.get_html()
<input type="text" name="blah" size="4" value="3.141592">
>>> type( p.from_html( "36.1", trans ) )
<type 'float'>
>>> type( p.from_html( "bleh", trans ) )
Traceback (most recent call last):
...
ValueError: A real number or workflow parameter e.g. ${name} is required
"""
dict_collection_visible_keys = ToolParameter.dict_collection_visible_keys + ( 'min', 'max' )
def __init__( self, tool, input_source ):
input_source = ensure_input_source(input_source)
TextToolParameter.__init__( self, tool, input_source )
self.min = input_source.get( 'min' )
self.max = input_source.get( 'max' )
if self.value:
try:
float( self.value )
except:
raise ValueError( "A real number is required" )
elif self.value is None and not self.optional:
raise ValueError( "The settings for this field require a 'value' setting and optionally a default value which must be a real number" )
if self.min:
try:
self.min = float( self.min )
except:
raise ValueError( "A real number is required" )
if self.max:
try:
self.max = float( self.max )
except:
raise ValueError( "A real number is required" )
if self.min is not None or self.max is not None:
self.validators.append( validation.InRangeValidator( None, self.min, self.max ) )
def get_html_field( self, trans=None, value=None, other_values={} ):
if isinstance( value, float ):
value = str( value )
return super( FloatToolParameter, self ).get_html_field( trans=trans, value=value, other_values=other_values )
def from_html( self, value, trans, other_values={} ):
try:
return float( value )
except:
if contains_workflow_parameter( value ) and trans.workflow_building_mode:
return value
if not value and self.optional:
return ""
if trans and trans.workflow_building_mode:
raise ValueError( "A real number or workflow parameter e.g. ${name} is required" )
else:
raise ValueError( "A real number is required" )
def to_python( self, value, app ):
try:
return float( value )
except Exception, err:
if contains_workflow_parameter(value):
return value
if not value and self.optional:
return None
raise err
def get_initial_value( self, trans, other_values ):
try:
return float( self.value )
except:
return None
class BooleanToolParameter( ToolParameter ):
"""
Parameter that takes one of two values.
>>> p = BooleanToolParameter( None, XML( '<param name="blah" type="boolean" checked="yes" truevalue="bulletproof vests" falsevalue="cellophane chests" />' ) )
>>> print p.name
blah
>>> print p.get_html()
<input type="checkbox" id="blah" name="blah" value="true" checked="checked"><input type="hidden" name="blah" value="true">
>>> print p.from_html( ["true","true"] )
True
>>> print p.to_param_dict_string( True )
bulletproof vests
>>> print p.from_html( ["true"] )
False
>>> print p.to_param_dict_string( False )
cellophane chests
"""
def __init__( self, tool, input_source ):
input_source = ensure_input_source(input_source)
ToolParameter.__init__( self, tool, input_source )
self.truevalue = input_source.get( 'truevalue', 'true' )
self.falsevalue = input_source.get( 'falsevalue', 'false' )
self.checked = input_source.get_bool( 'checked', False )
def get_html_field( self, trans=None, value=None, other_values={} ):
checked = self.checked
if value is not None:
checked = form_builder.CheckboxField.is_checked( value )
return form_builder.CheckboxField( self.name, checked, refresh_on_change=self.refresh_on_change )
def from_html( self, value, trans=None, other_values={} ):
return form_builder.CheckboxField.is_checked( value )
def from_json( self, value, trans=None, other_values={} ):
return string_as_bool( value )
def to_python( self, value, app ):
return ( value in [ 'True', 'true' ])
def get_initial_value( self, trans, other_values ):
return self.checked
def to_param_dict_string( self, value, other_values={} ):
if value:
return self.truevalue
else:
return self.falsevalue
def to_dict( self, trans, view='collection', value_mapper=None, other_values={} ):
d = super(BooleanToolParameter, self).to_dict(trans)
d['value'] = self.checked
d['truevalue'] = self.truevalue
d['falsevalue'] = self.falsevalue
return d
@property
def legal_values( self ):
return [ self.truevalue, self.falsevalue ]
class FileToolParameter( ToolParameter ):
"""
Parameter that takes an uploaded file as a value.
>>> p = FileToolParameter( None, XML( '<param name="blah" type="file"/>' ) )
>>> print p.name
blah
>>> print p.get_html()
<input type="file" name="blah">
>>> p = FileToolParameter( None, XML( '<param name="blah" type="file" ajax-upload="true"/>' ) )
>>> print p.get_html()
<input type="file" name="blah" galaxy-ajax-upload="true">
"""
def __init__( self, tool, input_source ):
"""
Example: C{<param name="bins" type="file" />}
"""
input_source = ensure_input_source(input_source)
ToolParameter.__init__( self, tool, input_source )
self.ajax = input_source.get_bool( 'ajax-upload', False )
def get_html_field( self, trans=None, value=None, other_values={} ):
return form_builder.FileField( self.name, ajax=self.ajax, value=value )
def from_html( self, value, trans=None, other_values={} ):
# Middleware or proxies may encode files in special ways (TODO: this
# should be pluggable)
if type( value ) == dict:
upload_store = trans.app.config.nginx_upload_store
assert upload_store, \
"Request appears to have been processed by nginx_upload_module \
but Galaxy is not configured to recognize it"
# Check that the file is in the right location
local_filename = os.path.abspath( value['path'] )
assert local_filename.startswith( upload_store ), \
"Filename provided by nginx (%s) is not in correct directory (%s)" % (local_filename, upload_store)
value = dict(
filename=value["name"],
local_filename=local_filename
)
return value
def get_required_enctype( self ):
"""
File upload elements require the multipart/form-data encoding
"""
return "multipart/form-data"
def to_string( self, value, app ):
if value in [ None, '' ]:
return None
elif isinstance( value, unicode ) or isinstance( value, str ):
return value
elif isinstance( value, dict ):
# or should we jsonify?
try:
return value['local_filename']
except:
return None
raise Exception( "FileToolParameter cannot be persisted" )
def to_python( self, value, app ):
if value is None:
return None
elif isinstance( value, unicode ) or isinstance( value, str ):
return value
else:
raise Exception( "FileToolParameter cannot be persisted" )
def get_initial_value( self, trans, other_values ):
return None
class FTPFileToolParameter( ToolParameter ):
"""
Parameter that takes a file uploaded via FTP as a value.
"""
def __init__( self, tool, input_source ):
"""
Example: C{<param name="bins" type="file" />}
"""
input_source = ensure_input_source(input_source)
ToolParameter.__init__( self, tool, input_source )
self.multiple = input_source.get_bool( 'multiple', True )
self.optional = input_source.parse_optional( True )
self.user_ftp_dir = ''
def get_initial_value( self, trans, other_values ):
if trans is not None:
if trans.user is not None:
self.user_ftp_dir = "%s/" % trans.user_ftp_dir
return None
@property
def visible( self ):
if self.tool.app.config.ftp_upload_dir is None or self.tool.app.config.ftp_upload_site is None:
return False
return True
def get_html_field( self, trans=None, value=None, other_values={} ):
if trans is None or trans.user is None:
user_ftp_dir = None
else:
user_ftp_dir = trans.user_ftp_dir
return form_builder.FTPFileField( self.name, user_ftp_dir, trans.app.config.ftp_upload_site, value=value )
def to_param_dict_string( self, value, other_values={} ):
if value is '':
return 'None'
lst = [ '%s%s' % (self.user_ftp_dir, dataset) for dataset in value ]
if self.multiple:
return lst
else:
return lst[ 0 ]
def from_html( self, value, trans=None, other_values={} ):
return self.to_python( value, trans.app, validate=True )
def to_string( self, value, app ):
return self.to_python( value, app )
def to_python( self, value, app, validate=False ):
if not isinstance( value, list ):
value = [ value ]
lst = []
for val in value:
if val in [ None, '' ]:
lst = []
break
if isinstance( val, dict ):
lst.append( val[ 'name' ] )
else:
lst.append( val )
if len( lst ) == 0:
if not self.optional and validate:
raise ValueError( "Please select a valid FTP file." )
return ''
if validate and self.tool.app.config.ftp_upload_dir is None:
raise ValueError( "The FTP directory is not configured." )
return lst
def to_dict( self, trans, view='collection', value_mapper=None, other_values=None ):
d = super( FTPFileToolParameter, self ).to_dict( trans )
d['multiple'] = self.multiple
return d
class HiddenToolParameter( ToolParameter ):
"""
Parameter that takes one of two values.
FIXME: This seems hacky, parameters should only describe things the user
might change. It is used for 'initializing' the UCSC proxy tool
>>> p = HiddenToolParameter( None, XML( '<param name="blah" type="hidden" value="wax so rockin"/>' ) )
>>> print p.name
blah
>>> print p.get_html()
<input type="hidden" name="blah" value="wax so rockin">
"""
def __init__( self, tool, input_source ):
input_source = ensure_input_source( input_source )
ToolParameter.__init__( self, tool, input_source )
self.value = input_source.get( 'value' )
self.hidden = True
def get_html_field( self, trans=None, value=None, other_values={} ):
return form_builder.HiddenField( self.name, self.value )
def get_initial_value( self, trans, other_values ):
return self.value
def get_label( self ):
return None
class ColorToolParameter( ToolParameter ):
"""
Parameter that stores a color.
>>> p = ColorToolParameter( None, XML( '<param name="blah" type="color" value="#ffffff"/>' ) )
>>> print p.name
blah
"""
def __init__( self, tool, input_source ):
input_source = ensure_input_source( input_source )
ToolParameter.__init__( self, tool, input_source )
self.value = input_source.get( 'value', '#fdeada' )
def get_html_field( self, trans=None, value=None, other_values={} ):
return form_builder.HiddenField( self.name, self.value )
def get_initial_value( self, trans, other_values ):
return self.value.lower()
class BaseURLToolParameter( HiddenToolParameter ):
"""
Returns a parameter that contains its value prepended by the
current server base url. Used in all redirects.
"""
def __init__( self, tool, input_source ):
input_source = ensure_input_source( input_source )
super( BaseURLToolParameter, self ).__init__( tool, input_source )
self.value = input_source.get( 'value', '' )
def get_initial_value( self, trans, other_values ):
return self._get_value()
def get_html_field( self, trans=None, value=None, other_values={} ):
return form_builder.HiddenField( self.name, self._get_value() )
def from_html( self, value=None, trans=None, other_values={} ):
return self._get_value()
def _get_value( self ):
try:
return url_for( self.value, qualified=True )
except Exception as e:
log.debug( 'Url creation failed for "%s": %s', self.name, e )
return self.value
def to_dict( self, trans, view='collection', value_mapper=None, other_values={} ):
d = super( BaseURLToolParameter, self ).to_dict( trans )
d[ 'value' ] = self._get_value()
return d
def DEFAULT_VALUE_MAP(x):
return x
def parse_dynamic_options(param, input_source):
options_elem = input_source.parse_dynamic_options_elem()
if options_elem is None:
options = None
else:
options = dynamic_options.DynamicOptions( options_elem, param )
return options
class SelectToolParameter( ToolParameter ):
"""
Parameter that takes on one (or many) or a specific set of values.
>>> p = SelectToolParameter( None, XML(
... '''
... <param name="blah" type="select">
... <option value="x">I am X</option>
... <option value="y" selected="true">I am Y</option>
... <option value="z">I am Z</option>
... </param>
... ''' ) )
>>> print p.name
blah
>>> print p.get_html()
<select name="blah" last_selected_value="y">
<option value="x">I am X</option>
<option value="y" selected>I am Y</option>
<option value="z">I am Z</option>
</select>
>>> print p.get_html( value="z" )
<select name="blah" last_selected_value="z">
<option value="x">I am X</option>
<option value="y">I am Y</option>
<option value="z" selected>I am Z</option>
</select>
>>> p = SelectToolParameter( None, XML(
... '''
... <param name="blah" type="select" multiple="true">
... <option value="x">I am X</option>
... <option value="y" selected="true">I am Y</option>
... <option value="z" selected="true">I am Z</option>
... </param>
... ''' ) )
>>> print p.name
blah
>>> print p.get_html()
<select name="blah" multiple last_selected_value="z">
<option value="x">I am X</option>
<option value="y" selected>I am Y</option>
<option value="z" selected>I am Z</option>
</select>
>>> print p.get_html( value=["x","y"])
<select name="blah" multiple last_selected_value="y">
<option value="x" selected>I am X</option>
<option value="y" selected>I am Y</option>
<option value="z">I am Z</option>
</select>
>>> print p.to_param_dict_string( ["y", "z"] )
y,z
>>> p = SelectToolParameter( None, XML(
... '''
... <param name="blah" type="select" multiple="true" display="checkboxes">
... <option value="x">I am X</option>
... <option value="y" selected="true">I am Y</option>
... <option value="z" selected="true">I am Z</option>
... </param>
... ''' ) )
>>> print p.name
blah
>>> print p.get_html()
<div class="checkUncheckAllPlaceholder" checkbox_name="blah"></div>
<div><input type="checkbox" name="blah" value="x" id="blah|x"><label class="inline" for="blah|x">I am X</label></div>
<div class="odd_row"><input type="checkbox" name="blah" value="y" id="blah|y" checked='checked'><label class="inline" for="blah|y">I am Y</label></div>
<div><input type="checkbox" name="blah" value="z" id="blah|z" checked='checked'><label class="inline" for="blah|z">I am Z</label></div>
>>> print p.get_html( value=["x","y"])
<div class="checkUncheckAllPlaceholder" checkbox_name="blah"></div>
<div><input type="checkbox" name="blah" value="x" id="blah|x" checked='checked'><label class="inline" for="blah|x">I am X</label></div>
<div class="odd_row"><input type="checkbox" name="blah" value="y" id="blah|y" checked='checked'><label class="inline" for="blah|y">I am Y</label></div>
<div><input type="checkbox" name="blah" value="z" id="blah|z"><label class="inline" for="blah|z">I am Z</label></div>
>>> print p.to_param_dict_string( ["y", "z"] )
y,z
"""
def __init__( self, tool, input_source, context=None ):
input_source = ensure_input_source( input_source )
ToolParameter.__init__( self, tool, input_source )
self.multiple = input_source.get_bool( 'multiple', False )
# Multiple selects are optional by default, single selection is the inverse.
self.optional = input_source.parse_optional( self.multiple )
self.display = input_source.get( 'display', None )
self.separator = input_source.get( 'separator', ',' )
self.legal_values = set()
self.dynamic_options = input_source.get( "dynamic_options", None )
self.options = parse_dynamic_options( self, input_source )
if self.options is not None:
for validator in self.options.validators:
self.validators.append( validator )
if self.dynamic_options is None and self.options is None:
self.static_options = input_source.parse_static_options()
for (title, value, selected) in self.static_options:
self.legal_values.add( value )
self.is_dynamic = ( ( self.dynamic_options is not None ) or ( self.options is not None ) )
def _get_dynamic_options_call_other_values( self, trans, other_values ):
call_other_values = ExpressionContext({ "__trans__": trans })
if other_values:
call_other_values.parent = other_values.parent
call_other_values.update( other_values.dict )
return call_other_values
def get_options( self, trans, other_values ):
if self.options:
return self.options.get_options( trans, other_values )
elif self.dynamic_options:
call_other_values = self._get_dynamic_options_call_other_values( trans, other_values )
try:
return eval( self.dynamic_options, self.tool.code_namespace, call_other_values )
except Exception, e:
log.debug( "Error determining dynamic options for parameter '%s' in tool '%s':", self.name, self.tool.id, exc_info=e )
return []
else:
return self.static_options
def get_legal_values( self, trans, other_values ):
if self.options:
return set( v for _, v, _ in self.options.get_options( trans, other_values ) )
elif self.dynamic_options:
try:
call_other_values = self._get_dynamic_options_call_other_values( trans, other_values )
return set( v for _, v, _ in eval( self.dynamic_options, self.tool.code_namespace, call_other_values ) )
except Exception, e:
log.debug( 'Determining legal values failed for "%s": %s', self.name, e )
return set()
else:
return self.legal_values
def get_html_field( self, trans=None, value=None, other_values={} ):
# Dynamic options are not yet supported in workflow, allow
# specifying the value as text for now.
options = list(self.get_options( trans, other_values ))
if len( list( options ) ) == 0 and trans.workflow_building_mode:
if self.multiple:
if value is None:
value = ""
else:
value = "\n".join( value )
return form_builder.TextArea( self.name, value=value )
else:
return form_builder.TextField( self.name, value=(value or "") )
if value is not None:
if not isinstance( value, list ):
value = [ value ]
field = form_builder.SelectField( self.name, self.multiple, self.display, self.refresh_on_change, refresh_on_change_values=self.refresh_on_change_values )
for text, optval, selected in options:
if value:
selected = ( optval in value )
field.add_option( text, optval, selected )
return field
def from_html( self, value, trans, other_values={} ):
legal_values = self.get_legal_values( trans, other_values )
if len(list(legal_values)) == 0 and trans.workflow_building_mode:
if self.multiple:
# While it is generally allowed that a select value can be '',
# we do not allow this to be the case in a dynamically
# generated multiple select list being set in workflow building
# mode we instead treat '' as 'No option Selected' (None)
if value == '':
value = None
else:
if isinstance( value, basestring ):
# Split on all whitespace. This not only provides flexibility
# in interpreting values but also is needed because many browsers
# use \r\n to separate lines.
value = value.split()
return value
if ( not legal_values or value is None ) and self.optional:
return None
if not legal_values:
raise ValueError( "Parameter %s requires a value, but has no legal values defined." % self.name )
if isinstance( value, list ):
if not self.repeat and not self.multiple:
raise ValueError( "Multiple values provided but parameter %s is not expecting multiple values." % self.name )
rval = []
for v in value:
if v not in legal_values:
raise ValueError( "An invalid option was selected for %s, %r, please verify." % ( self.name, v ) )
rval.append( v )
return rval
else:
value_is_none = ( value == "None" and "None" not in legal_values )
if value_is_none or not value:
if self.multiple:
if self.optional:
return []
else:
raise ValueError( "No option was selected for %s but input is not optional." % self.name )
if value not in legal_values:
raise ValueError( "An invalid option was selected for %s, %r, please verify." % ( self.name, value ) )
return value
def to_param_dict_string( self, value, other_values={}, value_map=DEFAULT_VALUE_MAP ):
if value is None:
return "None"
if isinstance( value, list ):
if not self.repeat and not self.multiple:
raise ValueError( "Multiple values provided but parameter %s is not expecting multiple values." % self.name )
value = map( str, value )
else:
value = str( value )
if self.tool is None or self.tool.options.sanitize:
if self.sanitizer:
value = self.sanitizer.sanitize_param( value )
else:
value = sanitize_param( value )
if isinstance( value, list ):
value = self.separator.join( map( value_map, value ) )
else:
value = value_map( value )
return value
def value_to_basic( self, value, app ):
if isinstance( value, RuntimeValue ):
# Need to handle runtime value's ourself since delegating to the
# parent method causes the value to be turned into a string, which
# breaks multiple selection
return { "__class__": "RuntimeValue" }
return value
def value_from_basic( self, value, app, ignore_errors=False ):
# Backward compatibility for unvalidated values already stored in databases
if isinstance( value, dict ) and value.get( "__class__", None ) == "UnvalidatedValue":
return value[ "value" ]
return super( SelectToolParameter, self ).value_from_basic( value, app, ignore_errors=ignore_errors )
def get_initial_value( self, trans, other_values ):
options = list( self.get_options( trans, other_values ) )
if len(options) == 0 and trans.workflow_building_mode:
return None
value = [ optval for _, optval, selected in options if selected ]
if len( value ) == 0:
if not self.optional and not self.multiple and options:
# Nothing selected, but not optional and not a multiple select, with some values,
# so we have to default to something (the HTML form will anyway)
value = options[0][1]
else:
value = None
elif len( value ) == 1:
value = value[0]
return value
def value_to_display_text( self, value, app ):
if not isinstance( value, list ):
value = [ value ]
# FIXME: Currently only translating values back to labels if they