5365: missed one updated signature update
[arvados.git] / apps / workbench / app / helpers / application_helper.rb
1 module ApplicationHelper
2   def current_user
3     controller.current_user
4   end
5
6   def self.match_uuid(uuid)
7     /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s)
8   end
9
10   def current_api_host
11     Rails.configuration.arvados_v1_base.gsub /https?:\/\/|\/arvados\/v1/,''
12   end
13
14   def render_markup(markup)
15     raw RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile) if markup
16   end
17
18   def human_readable_bytes_html(n)
19     return h(n) unless n.is_a? Fixnum
20     return "0 bytes" if (n == 0)
21
22     orders = {
23       1 => "bytes",
24       1024 => "KiB",
25       (1024*1024) => "MiB",
26       (1024*1024*1024) => "GiB",
27       (1024*1024*1024*1024) => "TiB"
28     }
29
30     orders.each do |k, v|
31       sig = (n.to_f/k)
32       if sig >=1 and sig < 1024
33         if v == 'bytes'
34           return "%i #{v}" % sig
35         else
36           return "%0.1f #{v}" % sig
37         end
38       end
39     end
40
41     return h(n)
42     #raw = n.to_s
43     #cooked = ''
44     #while raw.length > 3
45     #  cooked = ',' + raw[-3..-1] + cooked
46     #  raw = raw[0..-4]
47     #end
48     #cooked = raw + cooked
49   end
50
51   def resource_class_for_uuid(attrvalue, opts={})
52     ArvadosBase::resource_class_for_uuid(attrvalue, opts)
53   end
54
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.
62   #
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')))
69       if Rails.env.test?
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="')
73       else
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="')
78       end
79     else
80       super
81     end
82   end
83
84   ##
85   # Returns HTML that links to the Arvados object specified in +attrvalue+
86   # Provides various output control and styling options.
87   #
88   # +attrvalue+ an Arvados model object or uuid
89   #
90   # +opts+ a set of flags to control output:
91   #
92   # [:link_text] the link text to use (may include HTML), overrides everything else
93   #
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
96   #
97   # [:with_class_name] prefix the link text with the class name of the model
98   #
99   # [:no_tags] disable tags in the link text (default is to show tags).
100   # Currently tags are only shown for Collections.
101   #
102   # [:thumbnail] if the object is a collection, show an image thumbnail if the
103   # collection consists of a single image file.
104   #
105   # [:no_link] don't create a link, just return the link text
106   #
107   # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
108   #
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
112         object = attrvalue
113         link_uuid = attrvalue.uuid
114       else
115         object = nil
116         link_uuid = attrvalue
117       end
118       link_name = opts[:link_text]
119       tags = ""
120       if !link_name
121         link_name = object.andand.default_name || resource_class.default_name
122
123         if opts[:friendly_name]
124           if attrvalue.respond_to? :friendly_link_name
125             link_name = attrvalue.friendly_link_name opts[:lookup]
126           else
127             begin
128               if resource_class.name == 'Collection'
129                 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
130               else
131                 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
132               end
133             rescue ArvadosApiClient::NotFoundException
134               # If that lookup failed, the link will too. So don't make one.
135               return attrvalue
136             end
137           end
138         end
139         if link_name.nil? or link_name.empty?
140           link_name = attrvalue
141         end
142         if opts[:with_class_name]
143           link_name = "#{resource_class.to_s}: #{link_name}"
144         end
145         if !opts[:no_tags] and resource_class == Collection
146           links_for_object(link_uuid).each do |tag|
147             if tag.link_class.in? ["tag", "identifier"]
148               tags += ' <span class="label label-info">'
149               tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
150               tags += '</span>'
151             end
152           end
153         end
154         if opts[:thumbnail] and resource_class == Collection
155           # add an image thumbnail if the collection consists of a single image file.
156           collections_for_object(link_uuid).each do |c|
157             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
158               link_name += " "
159               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
160             end
161           end
162         end
163       end
164       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
165       if opts[:no_link] or (resource_class == User && !current_user)
166         raw(link_name)
167       else
168         (link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
169       end
170     else
171       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
172       if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
173         "(none)"
174       else
175         attrvalue
176       end
177     end
178   end
179
180   def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
181     resource_class = resource_class_for_uuid(attrvalue)
182     if !resource_class
183       return link_text_if_not_readable
184     end
185
186     if resource_class.to_s == 'Collection'
187       if CollectionsHelper.match(attrvalue)
188         readable = collection_for_pdh(attrvalue).any?
189       else
190         readable = collections_for_object(attrvalue).any?
191       end
192     else
193       readable = object_for_dataclass(resource_class, attrvalue)
194     end
195
196     if readable
197       link_to_if_arvados_object attrvalue, opts
198     else
199       link_text_if_not_readable
200     end
201   end
202
203   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
204     attrvalue = object.send(attr) if attrvalue.nil?
205     if not object.attribute_editable?(attr)
206       if attrvalue && attrvalue.length > 0
207         return render_attribute_as_textile( object, attr, attrvalue, false )
208       else
209         return (attr == 'name' and object.andand.default_name) ||
210                 '(none)'
211       end
212     end
213
214     input_type = 'text'
215     attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
216     if attrtype == 'text' or attr == 'description'
217       input_type = 'textarea'
218     elsif attrtype == 'datetime'
219       input_type = 'date'
220     else
221       input_type = 'text'
222     end
223
224     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
225     rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
226
227     ajax_options = {
228       "data-pk" => {
229         id: object.uuid,
230         key: object.class.to_s.underscore
231       }
232     }
233     if object.uuid
234       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
235     else
236       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
237       ajax_options['data-pk'][:defaults] = object.attributes
238     end
239     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
240     @unique_id ||= (Time.now.to_f*1000000).to_i
241     span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
242
243     span_tag = content_tag 'span', rendervalue, {
244       "data-emptytext" => '(none)',
245       "data-placement" => "bottom",
246       "data-type" => input_type,
247       "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
248       "data-name" => attr,
249       "data-object-uuid" => object.uuid,
250       "data-toggle" => "manual",
251       "data-value" => attrvalue,
252       "id" => span_id,
253       :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
254     }.merge(htmloptions).merge(ajax_options)
255     edit_tiptitle = 'edit'
256     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')
257     edit_button = raw('<a href="#" class="btn btn-xs btn-default btn-nodecorate" data-toggle="x-editable tooltip" data-toggle-selector="#' + span_id + '" data-placement="top" title="' + (htmloptions[:tiptitle] || edit_tiptitle) + '"><i class="fa fa-fw fa-pencil"></i></a>')
258     if htmloptions[:btnplacement] == :left
259       edit_button + ' ' + span_tag
260     else
261       span_tag + ' ' + edit_button
262     end
263   end
264
265   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
266     datatype = nil
267     required = true
268     attrvalue = value_info
269
270     if value_info.is_a? Hash
271       if value_info[:output_of]
272         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
273       end
274       if value_info[:dataclass]
275         dataclass = value_info[:dataclass]
276       end
277       if value_info[:optional] != nil
278         required = (value_info[:optional] != "true")
279       end
280       if value_info[:required] != nil
281         required = value_info[:required]
282       end
283
284       # Pick a suitable attrvalue to show as the current value (i.e.,
285       # the one that would be used if we ran the pipeline right now).
286       if value_info[:value]
287         attrvalue = value_info[:value]
288       elsif value_info[:default]
289         attrvalue = value_info[:default]
290       else
291         attrvalue = ''
292       end
293       preconfigured_search_str = value_info[:search_for]
294     end
295
296     if not object.andand.attribute_editable?(attr)
297       return link_to_arvados_object_if_readable(attrvalue, attrvalue)
298     end
299
300     if dataclass
301       begin
302         dataclass = dataclass.constantize
303       rescue NameError
304       end
305     else
306       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
307     end
308
309     id = "#{object.uuid}-#{subattr.join('-')}"
310     dn = "[#{attr}]"
311     subattr.each do |a|
312       dn += "[#{a}]"
313     end
314     if value_info.is_a? Hash
315       dn += '[value]'
316     end
317
318     if (dataclass == Collection) or (dataclass == File)
319       selection_param = object.class.to_s.underscore + dn
320       display_value = attrvalue
321       if value_info.is_a?(Hash)
322         if (link = Link.find? value_info[:link_uuid])
323           display_value = link.name
324         elsif value_info[:link_name]
325           display_value = value_info[:link_name]
326         elsif value_info[:selection_name]
327           display_value = value_info[:selection_name]
328         end
329       end
330       if (attr == :components) and (subattr.size > 2)
331         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
332       else
333         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
334       end
335       modal_path = choose_collections_path \
336       ({ title: chooser_title,
337          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
338          action_name: 'OK',
339          action_href: pipeline_instance_path(id: object.uuid),
340          action_method: 'patch',
341          preconfigured_search_str: (preconfigured_search_str || ""),
342          action_data: {
343            merge: true,
344            use_preview_selection: dataclass == File ? true : nil,
345            selection_param: selection_param,
346            success: 'page-refresh'
347          }.to_json,
348         })
349       return content_tag('div', :class => 'input-group') do
350         html = text_field_tag(dn, display_value,
351                               :class =>
352                               "form-control #{'required' if required}")
353         html + content_tag('span', :class => 'input-group-btn') do
354           link_to('Choose',
355                   modal_path,
356                   { :class => "btn btn-primary",
357                     :remote => true,
358                     :method => 'get',
359                   })
360         end
361       end
362     end
363
364     if attrvalue.is_a? String
365       datatype = 'text'
366     elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
367       # TODO: find a way to edit with x-editable
368       return attrvalue
369     end
370
371     # When datatype is a String or Fixnum, link_to the attrvalue
372     lt = link_to attrvalue, '#', {
373       "data-emptytext" => "none",
374       "data-placement" => "bottom",
375       "data-type" => datatype,
376       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
377       "data-title" => "Set value for #{subattr[-1].to_s}",
378       "data-name" => dn,
379       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
380       "data-value" => attrvalue,
381       # "clear" button interferes with form-control's up/down arrows
382       "data-clear" => false,
383       :class => "editable #{'required' if required} form-control",
384       :id => id
385     }.merge(htmloptions)
386
387     lt
388   end
389
390   def render_arvados_object_list_start(list, button_text, button_href,
391                                        params={}, *rest, &block)
392     show_max = params.delete(:show_max) || 3
393     params[:class] ||= 'btn btn-xs btn-default'
394     list[0...show_max].each { |item| yield item }
395     unless list[show_max].nil?
396       link_to(h(button_text) +
397               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
398               button_href, params, *rest)
399     end
400   end
401
402   def render_controller_partial partial, opts
403     cname = opts.delete :controller_name
404     begin
405       render opts.merge(partial: "#{cname}/#{partial}")
406     rescue ActionView::MissingTemplate
407       render opts.merge(partial: "application/#{partial}")
408     end
409   end
410
411   RESOURCE_CLASS_ICONS = {
412     "Collection" => "fa-archive",
413     "Group" => "fa-users",
414     "Human" => "fa-male",  # FIXME: Use a more inclusive icon.
415     "Job" => "fa-gears",
416     "KeepDisk" => "fa-hdd-o",
417     "KeepService" => "fa-exchange",
418     "Link" => "fa-arrows-h",
419     "Node" => "fa-cloud",
420     "PipelineInstance" => "fa-gears",
421     "PipelineTemplate" => "fa-gears",
422     "Repository" => "fa-code-fork",
423     "Specimen" => "fa-flask",
424     "Trait" => "fa-clipboard",
425     "User" => "fa-user",
426     "VirtualMachine" => "fa-terminal",
427   }
428   DEFAULT_ICON_CLASS = "fa-cube"
429
430   def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
431     RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
432   end
433
434   def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
435     fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
436   end
437
438   def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
439     case class_name = object.class.to_s
440     when "Group"
441       object.group_class ? 'fa-folder' : 'fa-users'
442     else
443       RESOURCE_CLASS_ICONS.fetch(class_name, default)
444     end
445   end
446
447   def chooser_preview_url_for object, use_preview_selection=false
448     case object.class.to_s
449     when 'Collection'
450       polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
451     else
452       nil
453     end
454   end
455
456   def render_attribute_as_textile( object, attr, attrvalue, truncate )
457     if attrvalue && (is_textile? object, attr)
458       markup = render_markup attrvalue
459       markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
460       return markup
461     else
462       return attrvalue
463     end
464   end
465
466   def render_localized_date(date, opts="")
467     raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
468   end
469
470 private
471   def is_textile?( object, attr )
472     is_textile = object.textile_attributes.andand.include?(attr)
473   end
474 end