1 module ApplicationHelper
3 controller.current_user
6 def self.match_uuid(uuid)
7 /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s)
11 Rails.configuration.arvados_v1_base.gsub /https?:\/\/|\/arvados\/v1/,''
14 def render_markup(markup)
15 raw RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile) if markup
18 def human_readable_bytes_html(n)
19 return h(n) unless n.is_a? Fixnum
20 return "0 bytes" if (n == 0)
26 (1024*1024*1024) => "GiB",
27 (1024*1024*1024*1024) => "TiB"
32 if sig >=1 and sig < 1024
34 return "%i #{v}" % sig
36 return "%0.1f #{v}" % sig
45 # cooked = ',' + raw[-3..-1] + cooked
48 #cooked = raw + cooked
51 def resource_class_for_uuid(attrvalue, opts={})
52 ArvadosBase::resource_class_for_uuid(attrvalue, opts)
55 # When using {remote:true}, or using {method:...} to use an HTTP
56 # method other than GET, move the target URI from href to
57 # data-remote-href. Otherwise, browsers offer features like "open in
58 # new window" and "copy link address" which bypass Rails' click
59 # handler and therefore end up at incorrect/nonexistent routes (by
60 # ignoring data-method) and expect to receive pages rather than
61 # javascript responses.
63 # See assets/javascripts/link_to_remote.js for supporting code.
64 def link_to *args, &block
65 if (args.last and args.last.is_a? Hash and
66 (args.last[:remote] or
67 (args.last[:method] and
68 args.last[:method].to_s.upcase != 'GET')))
70 # Capybara/phantomjs can't click_link without an href, even if
71 # the click handler means it never gets used.
72 raw super.gsub(' href="', ' href="#" data-remote-href="')
74 # Regular browsers work as desired: users can click A elements
75 # without hrefs, and click handlers fire; but there's no "copy
76 # link address" option in the right-click menu.
77 raw super.gsub(' href="', ' data-remote-href="')
85 # Returns HTML that links to the Arvados object specified in +attrvalue+
86 # Provides various output control and styling options.
88 # +attrvalue+ an Arvados model object or uuid
90 # +opts+ a set of flags to control output:
92 # [:link_text] the link text to use (may include HTML), overrides everything else
94 # [:friendly_name] whether to use the "friendly" name in the link text (by
95 # calling #friendly_link_name on the object), otherwise use the uuid
97 # [:with_class_name] prefix the link text with the class name of the model
99 # [:no_tags] disable tags in the link text (default is to show tags).
100 # Currently tags are only shown for Collections.
102 # [:thumbnail] if the object is a collection, show an image thumbnail if the
103 # collection consists of a single image file.
105 # [:no_link] don't create a link, just return the link text
107 # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
109 def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
110 if (resource_class = resource_class_for_uuid(attrvalue, opts))
111 if attrvalue.is_a? ArvadosBase
113 link_uuid = attrvalue.uuid
116 link_uuid = attrvalue
118 link_name = opts[:link_text]
121 link_name = object.andand.default_name || resource_class.default_name
123 if opts[:friendly_name]
124 if attrvalue.respond_to? :friendly_link_name
125 link_name = attrvalue.friendly_link_name opts[:lookup]
128 if resource_class.name == 'Collection'
129 if CollectionsHelper.match(link_uuid)
130 link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
132 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
135 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
137 rescue ArvadosApiClient::NotFoundException
138 # If that lookup failed, the link will too. So don't make one.
143 if link_name.nil? or link_name.empty?
144 link_name = attrvalue
146 if opts[:with_class_name]
147 link_name = "#{resource_class.to_s}: #{link_name}"
149 if !opts[:no_tags] and resource_class == Collection
150 links_for_object(link_uuid).each do |tag|
151 if tag.link_class.in? ["tag", "identifier"]
152 tags += ' <span class="label label-info">'
153 tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
158 if opts[:thumbnail] and resource_class == Collection
159 # add an image thumbnail if the collection consists of a single image file.
160 collections_for_object(link_uuid).each do |c|
161 if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
163 link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
168 style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
169 if opts[:no_link] or (resource_class == User && !current_user)
172 controller_class = resource_class.to_s.tableize
173 if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
174 controller_class = 'projects'
176 (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
179 # just return attrvalue if it is not recognizable as an Arvados object or uuid.
180 if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
188 def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
189 resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
191 return link_to_if_arvados_object attrvalue, opts
194 readable = object_readable attrvalue, resource_class
196 link_to_if_arvados_object attrvalue, opts
197 elsif opts[:required] and current_user # no need to show this for anonymous user
198 raw('<div><input type="text" style="border:none;width:100%;background:#ffdddd" disabled=true class="required unreadable-input" value="') + link_text_if_not_readable + raw('" ></input></div>')
200 link_text_if_not_readable
204 # This method takes advantage of preloaded collections and objects.
205 # Hence you can improve performance by first preloading objects
206 # related to the page context before using this method.
207 def object_readable attrvalue, resource_class=nil
208 # if it is a collection filename, check readable for the locator
209 attrvalue = attrvalue.split('/')[0] if attrvalue
211 resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
212 return if resource_class.nil?
215 if resource_class.to_s == 'Collection'
216 if CollectionsHelper.match(attrvalue)
217 found = collection_for_pdh(attrvalue)
218 return_value = found.first if found.any?
220 found = collections_for_object(attrvalue)
221 return_value = found.first if found.any?
224 return_value = object_for_dataclass(resource_class, attrvalue)
229 # Render an editable attribute with the attrvalue of the attr.
230 # The htmloptions are added to the editable element's list of attributes.
231 # The nonhtml_options are only used to customize the display of the element.
232 def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
233 attrvalue = object.send(attr) if attrvalue.nil?
234 if not object.attribute_editable?(attr)
235 if attrvalue && attrvalue.length > 0
236 return render_attribute_as_textile( object, attr, attrvalue, false )
238 return (attr == 'name' and object.andand.default_name) ||
244 attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
245 if attrtype == 'text' or attr == 'description'
246 input_type = 'textarea'
247 elsif attrtype == 'datetime'
253 attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
254 rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
259 key: object.class.to_s.underscore
263 ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
265 ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
266 ajax_options['data-pk'][:defaults] = object.attributes
268 ajax_options['data-pk'] = ajax_options['data-pk'].to_json
269 @unique_id ||= (Time.now.to_f*1000000).to_i
270 span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
272 span_tag = content_tag 'span', rendervalue, {
273 "data-emptytext" => '(none)',
274 "data-placement" => "bottom",
275 "data-type" => input_type,
276 "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
277 "data-name" => htmloptions['selection_name'] || attr,
278 "data-object-uuid" => object.uuid,
279 "data-toggle" => "manual",
280 "data-value" => htmloptions['data-value'] || attrvalue,
282 :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
283 }.merge(htmloptions).merge(ajax_options)
285 edit_tiptitle = 'edit'
286 edit_tiptitle = 'Warning: do not use hyphens in the repository name as they will be stripped' if (object.class.to_s == 'Repository' and attr == 'name')
288 edit_button = raw('<a href="#" class="btn btn-xs btn-' + (nonhtml_options[:btnclass] || 'default') + ' btn-nodecorate" data-toggle="x-editable tooltip" data-toggle-selector="#' + span_id + '" data-placement="top" title="' + (nonhtml_options[:tiptitle] || edit_tiptitle) + '"><i class="fa fa-fw fa-pencil"></i>' + (nonhtml_options[:btntext] || '') + '</a>')
290 if nonhtml_options[:btnplacement] == :left
291 edit_button + ' ' + span_tag
292 elsif nonhtml_options[:btnplacement] == :top
293 edit_button + raw('<br/>') + span_tag
295 span_tag + ' ' + edit_button
299 def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
302 attrvalue = value_info
304 if value_info.is_a? Hash
305 if value_info[:output_of]
306 return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
308 if value_info[:dataclass]
309 dataclass = value_info[:dataclass]
311 if value_info[:optional] != nil
312 required = (value_info[:optional] != "true")
314 if value_info[:required] != nil
315 required = value_info[:required]
318 # Pick a suitable attrvalue to show as the current value (i.e.,
319 # the one that would be used if we ran the pipeline right now).
320 if value_info[:value]
321 attrvalue = value_info[:value]
322 elsif value_info[:default]
323 attrvalue = value_info[:default]
327 preconfigured_search_str = value_info[:search_for]
330 if not object.andand.attribute_editable?(attr)
331 return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
336 dataclass = dataclass.constantize
340 dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
343 id = "#{object.uuid}-#{subattr.join('-')}"
348 if value_info.is_a? Hash
352 if (dataclass == Collection) or (dataclass == File)
353 selection_param = object.class.to_s.underscore + dn
354 display_value = attrvalue
355 if value_info.is_a?(Hash)
356 if (link = Link.find? value_info[:link_uuid])
357 display_value = link.name
358 elsif value_info[:link_name]
359 display_value = value_info[:link_name]
360 elsif value_info[:selection_name]
361 display_value = value_info[:selection_name]
364 if (attr == :components) and (subattr.size > 2)
365 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
367 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
369 modal_path = choose_collections_path \
370 ({ title: chooser_title,
371 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
373 action_href: pipeline_instance_path(id: object.uuid),
374 action_method: 'patch',
375 preconfigured_search_str: (preconfigured_search_str || ""),
378 use_preview_selection: dataclass == File ? true : nil,
379 selection_param: selection_param,
380 success: 'page-refresh'
384 return content_tag('div', :class => 'input-group') do
385 html = text_field_tag(dn, display_value,
387 "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
388 html + content_tag('span', :class => 'input-group-btn') do
391 { :class => "btn btn-primary",
399 if attrvalue.is_a? String
401 elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
402 # TODO: find a way to edit with x-editable
406 # When datatype is a String or Fixnum, link_to the attrvalue
407 lt = link_to attrvalue, '#', {
408 "data-emptytext" => "none",
409 "data-placement" => "bottom",
410 "data-type" => datatype,
411 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
412 "data-title" => "Set value for #{subattr[-1].to_s}",
414 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
415 "data-value" => attrvalue,
416 # "clear" button interferes with form-control's up/down arrows
417 "data-clear" => false,
418 :class => "editable #{'required' if required} form-control",
425 def get_cwl_inputs(workflow)
427 return workflow[:inputs]
429 workflow[:"$graph"].each do |tool|
430 if tool[:id] == "#main"
437 def cwl_shortname(id)
441 return id.split("/")[-1]
444 def cwl_input_info(input_schema)
445 required = !(input_schema[:type].include? "null")
446 if input_schema[:type].is_a? Array
447 primary_type = input_schema[:type].select { |n| n != "null" }[0]
448 elsif input_schema[:type].is_a? String
449 primary_type = input_schema[:type]
450 elsif input_schema[:type].is_a? Hash
451 primary_type = input_schema[:type]
453 param_id = cwl_shortname(input_schema[:id])
454 return required, primary_type, param_id
457 def cwl_input_value(object, input_schema, set_attr_path)
460 set_attr_path.each do |a|
462 attrvalue = attrvalue[a.to_sym]
467 def cwl_inputs_required(object, inputs_schema, set_attr_path)
469 inputs_schema.each do |input|
470 required, primary_type, param_id = cwl_input_info(input)
471 dn, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
472 r += 1 if required and attrvalue.nil?
477 def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
478 required, primary_type, param_id = cwl_input_info(input_schema)
480 dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
481 attrvalue = if attrvalue.nil? then "" else attrvalue end
483 id = "#{object.uuid}-#{param_id}"
485 opt_empty_selection = if required then [] else [{value: "", text: ""}] end
487 if ["Directory", "File"].include? primary_type
488 chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
489 selection_param = object.class.to_s.underscore + dn
490 if attrvalue.is_a? Hash
491 display_value = attrvalue[:"arv:collection"] || attrvalue[:location]
492 re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
495 display_value = "#{Collection.find(re[1]).name} / #{re[4][1..-1]}"
497 display_value = Collection.find(re[1]).name
501 modal_path = choose_collections_path \
502 ({ title: chooser_title,
503 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
505 action_href: container_request_path(id: object.uuid),
506 action_method: 'patch',
507 preconfigured_search_str: "",
510 use_preview_selection: primary_type == 'File' ? true : nil,
511 selection_param: selection_param,
512 success: 'page-refresh'
516 return content_tag('div', :class => 'input-group') do
517 html = text_field_tag(dn, display_value,
519 "form-control #{'required' if required}")
520 html + content_tag('span', :class => 'input-group-btn') do
523 { :class => "btn btn-primary",
529 elsif "boolean" == primary_type
530 return link_to attrvalue.to_s, '#', {
531 "data-emptytext" => "none",
532 "data-placement" => "bottom",
533 "data-type" => "select",
534 "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
535 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
536 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
538 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
539 "data-value" => attrvalue.to_s,
540 # "clear" button interferes with form-control's up/down arrows
541 "data-clear" => false,
542 :class => "editable #{'required' if required} form-control",
545 elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
546 return link_to attrvalue, '#', {
547 "data-emptytext" => "none",
548 "data-placement" => "bottom",
549 "data-type" => "select",
550 "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
551 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
552 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
554 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
555 "data-value" => attrvalue,
556 # "clear" button interferes with form-control's up/down arrows
557 "data-clear" => false,
558 :class => "editable #{'required' if required} form-control",
561 elsif primary_type.is_a? String
562 if ["int", "long"].include? primary_type
568 return link_to attrvalue, '#', {
569 "data-emptytext" => "none",
570 "data-placement" => "bottom",
571 "data-type" => datatype,
572 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
573 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
575 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
576 "data-value" => attrvalue,
577 # "clear" button interferes with form-control's up/down arrows
578 "data-clear" => false,
579 :class => "editable #{'required' if required} form-control",
583 return "Unable to render editing control for parameter type #{primary_type}"
587 def render_arvados_object_list_start(list, button_text, button_href,
588 params={}, *rest, &block)
589 show_max = params.delete(:show_max) || 3
590 params[:class] ||= 'btn btn-xs btn-default'
591 list[0...show_max].each { |item| yield item }
592 unless list[show_max].nil?
593 link_to(h(button_text) +
594 raw(' <i class="fa fa-fw fa-arrow-circle-right"></i>'),
595 button_href, params, *rest)
599 def render_controller_partial partial, opts
600 cname = opts.delete :controller_name
602 render opts.merge(partial: "#{cname}/#{partial}")
603 rescue ActionView::MissingTemplate
604 render opts.merge(partial: "application/#{partial}")
608 RESOURCE_CLASS_ICONS = {
609 "Collection" => "fa-archive",
610 "ContainerRequest" => "fa-gears",
611 "Group" => "fa-users",
612 "Human" => "fa-male", # FIXME: Use a more inclusive icon.
614 "KeepDisk" => "fa-hdd-o",
615 "KeepService" => "fa-exchange",
616 "Link" => "fa-arrows-h",
617 "Node" => "fa-cloud",
618 "PipelineInstance" => "fa-gears",
619 "PipelineTemplate" => "fa-gears",
620 "Repository" => "fa-code-fork",
621 "Specimen" => "fa-flask",
622 "Trait" => "fa-clipboard",
624 "VirtualMachine" => "fa-terminal",
625 "Workflow" => "fa-gears",
627 DEFAULT_ICON_CLASS = "fa-cube"
629 def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
630 RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
633 def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
634 fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
637 def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
638 case class_name = object.class.to_s
640 object.group_class ? 'fa-folder' : 'fa-users'
642 RESOURCE_CLASS_ICONS.fetch(class_name, default)
646 def chooser_preview_url_for object, use_preview_selection=false
647 case object.class.to_s
649 polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
655 def render_attribute_as_textile( object, attr, attrvalue, truncate )
656 if attrvalue && (is_textile? object, attr)
657 markup = render_markup attrvalue
658 markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
665 def render_localized_date(date, opts="")
666 raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
669 def render_time duration, use_words, round_to_min=true
670 render_runtime duration, use_words, round_to_min
674 def is_textile?( object, attr )
675 is_textile = object.textile_attributes.andand.include?(attr)