Merge branch 'master' into 3354-render-textile
[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_content_from_database(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   ##
56   # Returns HTML that links to the Arvados object specified in +attrvalue+
57   # Provides various output control and styling options.
58   #
59   # +attrvalue+ an Arvados model object or uuid
60   #
61   # +opts+ a set of flags to control output:
62   #
63   # [:link_text] the link text to use (may include HTML), overrides everything else
64   #
65   # [:friendly_name] whether to use the "friendly" name in the link text (by
66   # calling #friendly_link_name on the object), otherwise use the uuid
67   #
68   # [:with_class_name] prefix the link text with the class name of the model
69   #
70   # [:no_tags] disable tags in the link text (default is to show tags).
71   # Currently tags are only shown for Collections.
72   #
73   # [:thumbnail] if the object is a collection, show an image thumbnail if the
74   # collection consists of a single image file.
75   #
76   # [:no_link] don't create a link, just return the link text
77   #
78   # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
79   #
80   def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
81     if (resource_class = resource_class_for_uuid(attrvalue, opts))
82       if attrvalue.is_a? ArvadosBase
83         object = attrvalue
84         link_uuid = attrvalue.uuid
85       else
86         object = nil
87         link_uuid = attrvalue
88       end
89       link_name = opts[:link_text]
90       if !link_name
91         link_name = object.andand.default_name || resource_class.default_name
92
93         if opts[:friendly_name]
94           if attrvalue.respond_to? :friendly_link_name
95             link_name = attrvalue.friendly_link_name
96           else
97             begin
98               if resource_class.name == 'Collection'
99                 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
100               else
101                 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
102               end
103             rescue ArvadosApiClient::NotFoundException
104               # If that lookup failed, the link will too. So don't make one.
105               return attrvalue
106             end
107           end
108         end
109         if opts[:with_class_name]
110           link_name = "#{resource_class.to_s}: #{link_name}"
111         end
112         if !opts[:no_tags] and resource_class == Collection
113           links_for_object(link_uuid).each do |tag|
114             if tag.link_class.in? ["tag", "identifier"]
115               link_name += ' <span class="label label-info">' + html_escape(tag.name) + '</span>'
116             end
117           end
118         end
119         if opts[:thumbnail] and resource_class == Collection
120           # add an image thumbnail if the collection consists of a single image file.
121           collections_for_object(link_uuid).each do |c|
122             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
123               link_name += " "
124               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
125             end
126           end
127         end
128       end
129       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
130       if opts[:no_link]
131         raw(link_name)
132       else
133         link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts
134       end
135     else
136       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
137       attrvalue
138     end
139   end
140
141   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
142     attrvalue = object.send(attr) if attrvalue.nil?
143     if !object.attribute_editable?(attr, :ever) or
144         (!object.editable? and
145          !object.owner_uuid.in?(my_projects.collect(&:uuid)))
146       if attrvalue && attrvalue.length > 0
147         return render_textile_if_textile( object, attr, attrvalue )
148       else
149         return (attr == 'name' and object.andand.default_name) ||
150                 '(none)'
151       end
152     end
153
154     input_type = 'text'
155     case object.class.attribute_info[attr.to_sym].andand[:type]
156     when 'text'
157       input_type = 'textarea'
158     when 'datetime'
159       input_type = 'date'
160     else
161       input_type = 'text'
162     end
163
164     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
165     rendervalue = render_textile_if_textile( object, attr, attrvalue )
166
167     ajax_options = {
168       "data-pk" => {
169         id: object.uuid,
170         key: object.class.to_s.underscore
171       }
172     }
173     if object.uuid
174       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
175     else
176       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
177       ajax_options['data-pk'][:defaults] = object.attributes
178     end
179     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
180     @unique_id ||= (Time.now.to_f*1000000).to_i
181     span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
182
183     span_tag = content_tag 'span', rendervalue, {
184       "data-emptytext" => (object.andand.default_name || 'none'),
185       "data-placement" => "bottom",
186       "data-type" => input_type,
187       "data-title" => "Edit #{attr.gsub '_', ' '}",
188       "data-name" => attr,
189       "data-object-uuid" => object.uuid,
190       "data-toggle" => "manual",
191       "data-value" => attrvalue,
192       "id" => span_id,
193       :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
194     }.merge(htmloptions).merge(ajax_options)
195     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') + '"><i class="fa fa-fw fa-pencil"></i></a>')
196     if htmloptions[:btnplacement] == :left
197       edit_button + ' ' + span_tag
198     else
199       span_tag + ' ' + edit_button
200     end
201   end
202
203   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
204     datatype = nil
205     required = true
206     attrvalue = value_info
207
208     if value_info.is_a? Hash
209       if value_info[:output_of]
210         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
211       end
212       if value_info[:dataclass]
213         dataclass = value_info[:dataclass]
214       end
215       if value_info[:optional] != nil
216         required = (value_info[:optional] != "true")
217       end
218       if value_info[:required] != nil
219         required = value_info[:required]
220       end
221
222       # Pick a suitable attrvalue to show as the current value (i.e.,
223       # the one that would be used if we ran the pipeline right now).
224       if value_info[:value]
225         attrvalue = value_info[:value]
226       elsif value_info[:default]
227         attrvalue = value_info[:default]
228       else
229         attrvalue = ''
230       end
231     end
232
233     if !object or
234         !object.attribute_editable?(attr, :ever) or
235         (!object.editable? and
236          !object.owner_uuid.in?(my_projects.collect(&:uuid)))
237       return link_to_if_arvados_object attrvalue
238     end
239
240     if dataclass
241       begin
242         dataclass = dataclass.constantize
243       rescue NameError
244       end
245     else
246       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
247     end
248
249     id = "#{object.uuid}-#{subattr.join('-')}"
250     dn = "[#{attr}]"
251     subattr.each do |a|
252       dn += "[#{a}]"
253     end
254     if value_info.is_a? Hash
255       dn += '[value]'
256     end
257
258     if dataclass == Collection
259       selection_param = object.class.to_s.underscore + dn
260       display_value = attrvalue
261       if value_info.is_a?(Hash)
262         if (link = Link.find? value_info[:link_uuid])
263           display_value = link.name
264         elsif value_info[:link_name]
265           display_value = value_info[:link_name]
266         end
267       end
268       if (attr == :components) and (subattr.size > 2)
269         chooser_title = "Choose a dataset for #{object.component_input_title(subattr[0], subattr[2])}:"
270       else
271         chooser_title = "Choose a dataset:"
272       end
273       modal_path = choose_collections_path \
274       ({ title: chooser_title,
275          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
276          action_name: 'OK',
277          action_href: pipeline_instance_path(id: object.uuid),
278          action_method: 'patch',
279          preconfigured_search_str: "#{value_info[:search_for]}",
280          action_data: {
281            merge: true,
282            selection_param: selection_param,
283            success: 'page-refresh'
284          }.to_json,
285         })
286       return content_tag('div', :class => 'input-group') do
287         html = text_field_tag(dn, display_value,
288                               :class =>
289                               "form-control #{'required' if required}")
290         html + content_tag('span', :class => 'input-group-btn') do
291           link_to('Choose',
292                   modal_path,
293                   { :class => "btn btn-primary",
294                     :remote => true,
295                     :method => 'get',
296                   })
297         end
298       end
299     end
300
301     if dataclass.andand.is_a?(Class)
302       datatype = 'select'
303     elsif dataclass == 'number'
304       datatype = 'number'
305     elsif attrvalue.is_a? Array
306       # TODO: find a way to edit arrays with x-editable
307       return attrvalue
308     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
309       datatype = 'number'
310     elsif attrvalue.is_a? String
311       datatype = 'text'
312     end
313
314     # preload data
315     preload_uuids = []
316     items = []
317     selectables = []
318
319     attrtext = attrvalue
320     if dataclass.is_a? Class and dataclass < ArvadosBase
321       objects = get_n_objects_of_class dataclass, 10
322       objects.each do |item|
323         items << item
324         preload_uuids << item.uuid
325       end
326       if attrvalue and !attrvalue.empty?
327         preload_uuids << attrvalue
328       end
329       preload_links_for_objects preload_uuids
330
331       if attrvalue and !attrvalue.empty?
332         links_for_object(attrvalue).each do |link|
333           if link.link_class.in? ["tag", "identifier"]
334             attrtext += " [#{link.name}]"
335           end
336         end
337         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
338       end
339       itemuuids = []
340       items.each do |item|
341         itemuuids << item.uuid
342         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
343       end
344
345       itemuuids.each do |itemuuid|
346         links_for_object(itemuuid).each do |link|
347           if link.link_class.in? ["tag", "identifier"]
348             selectables.each do |selectable|
349               if selectable['uuid'] == link.head_uuid
350                 selectable['name'] += ' [' + link.name + ']'
351               end
352             end
353           end
354         end
355       end
356     end
357
358     lt = link_to attrtext, '#', {
359       "data-emptytext" => "none",
360       "data-placement" => "bottom",
361       "data-type" => datatype,
362       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
363       "data-title" => "Set value for #{subattr[-1].to_s}",
364       "data-name" => dn,
365       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
366       "data-value" => attrvalue,
367       # "clear" button interferes with form-control's up/down arrows
368       "data-clear" => false,
369       :class => "editable #{'required' if required} form-control",
370       :id => id
371     }.merge(htmloptions)
372
373     lt += raw("\n<script>")
374
375     if selectables.any?
376       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
377     end
378
379     lt += raw("$('[data-name=\"#{dn}\"]').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
380
381     lt += raw("</script>")
382
383     lt
384   end
385
386   def render_arvados_object_list_start(list, button_text, button_href,
387                                        params={}, *rest, &block)
388     show_max = params.delete(:show_max) || 3
389     params[:class] ||= 'btn btn-xs btn-default'
390     list[0...show_max].each { |item| yield item }
391     unless list[show_max].nil?
392       link_to(h(button_text) +
393               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
394               button_href, params, *rest)
395     end
396   end
397
398   def render_controller_partial partial, opts
399     cname = opts.delete :controller_name
400     begin
401       render opts.merge(partial: "#{cname}/#{partial}")
402     rescue ActionView::MissingTemplate
403       render opts.merge(partial: "application/#{partial}")
404     end
405   end
406
407   RESOURCE_CLASS_ICONS = {
408     "Collection" => "fa-archive",
409     "Group" => "fa-users",
410     "Human" => "fa-male",  # FIXME: Use a more inclusive icon.
411     "Job" => "fa-gears",
412     "KeepDisk" => "fa-hdd-o",
413     "KeepService" => "fa-exchange",
414     "Link" => "fa-arrows-h",
415     "Node" => "fa-cloud",
416     "PipelineInstance" => "fa-gears",
417     "PipelineTemplate" => "fa-gears",
418     "Repository" => "fa-code-fork",
419     "Specimen" => "fa-flask",
420     "Trait" => "fa-clipboard",
421     "User" => "fa-user",
422     "VirtualMachine" => "fa-terminal",
423   }
424   DEFAULT_ICON_CLASS = "fa-cube"
425
426   def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
427     RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
428   end
429
430   def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
431     fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
432   end
433
434   def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
435     case class_name = object.class.to_s
436     when "Group"
437       object.group_class ? 'fa-folder' : 'fa-users'
438     else
439       RESOURCE_CLASS_ICONS.fetch(class_name, default)
440     end
441   end
442
443   def chooser_preview_url_for object
444     case object.class.to_s
445     when 'Collection'
446       polymorphic_path(object, tab_pane: 'chooser_preview')
447     else
448       nil
449     end
450   end
451
452 private
453   def is_textile?( object, attr )
454     is_textile = object.textile_attributes.andand.include?(attr)
455   end
456
457   def render_textile_if_textile( object, attr, attrvalue )
458     is_textile?( object, attr ) ? render_content_from_database(attrvalue) : attrvalue
459   end
460 end