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