Merge branch '2891-improve-workbench-errors'
[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_html
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       return ((attrvalue && attrvalue.length > 0 && attrvalue) ||
147               (attr == 'name' and object.andand.default_name) ||
148               '(none)')
149     end
150
151     input_type = 'text'
152     case object.class.attribute_info[attr.to_sym].andand[:type]
153     when 'text'
154       input_type = 'textarea'
155     when 'datetime'
156       input_type = 'date'
157     else
158       input_type = 'text'
159     end
160
161     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
162
163     ajax_options = {
164       "data-pk" => {
165         id: object.uuid,
166         key: object.class.to_s.underscore
167       }
168     }
169     if object.uuid
170       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
171     else
172       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
173       ajax_options['data-pk'][:defaults] = object.attributes
174     end
175     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
176     @unique_id ||= (Time.now.to_f*1000000).to_i
177     span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
178
179     span_tag = content_tag 'span', attrvalue.to_s, {
180       "data-emptytext" => (object.andand.default_name || 'none'),
181       "data-placement" => "bottom",
182       "data-type" => input_type,
183       "data-title" => "Edit #{attr.gsub '_', ' '}",
184       "data-name" => attr,
185       "data-object-uuid" => object.uuid,
186       "data-toggle" => "manual",
187       "id" => span_id,
188       :class => "editable"
189     }.merge(htmloptions).merge(ajax_options)
190     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>')
191     if htmloptions[:btnplacement] == :left
192       edit_button + ' ' + span_tag
193     else
194       span_tag + ' ' + edit_button
195     end
196   end
197
198   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
199     datatype = nil
200     required = true
201     attrvalue = value_info
202
203     if value_info.is_a? Hash
204       if value_info[:output_of]
205         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
206       end
207       if value_info[:dataclass]
208         dataclass = value_info[:dataclass]
209       end
210       if value_info[:optional] != nil
211         required = (value_info[:optional] != "true")
212       end
213       if value_info[:required] != nil
214         required = value_info[:required]
215       end
216
217       # Pick a suitable attrvalue to show as the current value (i.e.,
218       # the one that would be used if we ran the pipeline right now).
219       if value_info[:value]
220         attrvalue = value_info[:value]
221       elsif value_info[:default]
222         attrvalue = value_info[:default]
223       else
224         attrvalue = ''
225       end
226     end
227
228     if !object or
229         !object.attribute_editable?(attr, :ever) or
230         (!object.editable? and
231          !object.owner_uuid.in?(my_projects.collect(&:uuid)))
232       return link_to_if_arvados_object attrvalue
233     end
234
235     if dataclass
236       begin
237         dataclass = dataclass.constantize
238       rescue NameError
239       end
240     else
241       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
242     end
243
244     id = "#{object.uuid}-#{subattr.join('-')}"
245     dn = "[#{attr}]"
246     subattr.each do |a|
247       dn += "[#{a}]"
248     end
249     if value_info.is_a? Hash
250       dn += '[value]'
251     end
252
253     if dataclass == Collection
254       selection_param = object.class.to_s.underscore + dn
255       display_value = attrvalue
256       if value_info.is_a?(Hash)
257         if (link = Link.find? value_info[:link_uuid])
258           display_value = link.name
259         elsif value_info[:link_name]
260           display_value = value_info[:link_name]
261         end
262       end
263       modal_path = choose_collections_path \
264       ({ title: 'Choose a dataset:',
265          filters: [['tail_uuid', '=', object.owner_uuid]].to_json,
266          action_name: 'OK',
267          action_href: pipeline_instance_path(id: object.uuid),
268          action_method: 'patch',
269          action_data: {
270            merge: true,
271            selection_param: selection_param,
272            success: 'page-refresh'
273          }.to_json,
274         })
275       return content_tag('div', :class => 'input-group') do
276         html = text_field_tag(dn, display_value,
277                               :class =>
278                               "form-control #{'required' if required}")
279         html + content_tag('span', :class => 'input-group-btn') do
280           link_to('Choose',
281                   modal_path,
282                   { :class => "btn btn-primary",
283                     :remote => true,
284                     :method => 'get',
285                   })
286         end
287       end
288     end
289
290     if dataclass.andand.is_a?(Class)
291       datatype = 'select'
292     elsif dataclass == 'number'
293       datatype = 'number'
294     elsif attrvalue.is_a? Array
295       # TODO: find a way to edit arrays with x-editable
296       return attrvalue
297     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
298       datatype = 'number'
299     elsif attrvalue.is_a? String
300       datatype = 'text'
301     end
302
303     # preload data
304     preload_uuids = []
305     items = []
306     selectables = []
307
308     attrtext = attrvalue
309     if dataclass.is_a? Class and dataclass < ArvadosBase
310       objects = get_n_objects_of_class dataclass, 10
311       objects.each do |item|
312         items << item
313         preload_uuids << item.uuid
314       end
315       if attrvalue and !attrvalue.empty?
316         preload_uuids << attrvalue
317       end
318       preload_links_for_objects preload_uuids
319
320       if attrvalue and !attrvalue.empty?
321         links_for_object(attrvalue).each do |link|
322           if link.link_class.in? ["tag", "identifier"]
323             attrtext += " [#{link.name}]"
324           end
325         end
326         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
327       end
328       itemuuids = []
329       items.each do |item|
330         itemuuids << item.uuid
331         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
332       end
333
334       itemuuids.each do |itemuuid|
335         links_for_object(itemuuid).each do |link|
336           if link.link_class.in? ["tag", "identifier"]
337             selectables.each do |selectable|
338               if selectable['uuid'] == link.head_uuid
339                 selectable['name'] += ' [' + link.name + ']'
340               end
341             end
342           end
343         end
344       end
345     end
346
347     lt = link_to attrtext, '#', {
348       "data-emptytext" => "none",
349       "data-placement" => "bottom",
350       "data-type" => datatype,
351       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
352       "data-title" => "Set value for #{subattr[-1].to_s}",
353       "data-name" => dn,
354       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
355       "data-value" => attrvalue,
356       # "clear" button interferes with form-control's up/down arrows
357       "data-clear" => false,
358       :class => "editable #{'required' if required} form-control",
359       :id => id
360     }.merge(htmloptions)
361
362     lt += raw("\n<script>")
363
364     if selectables.any?
365       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
366     end
367
368     lt += raw("$('[data-name=\"#{dn}\"]').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
369
370     lt += raw("</script>")
371
372     lt
373   end
374
375   def render_arvados_object_list_start(list, button_text, button_href,
376                                        params={}, *rest, &block)
377     show_max = params.delete(:show_max) || 3
378     params[:class] ||= 'btn btn-xs btn-default'
379     list[0...show_max].each { |item| yield item }
380     unless list[show_max].nil?
381       link_to(h(button_text) +
382               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
383               button_href, params, *rest)
384     end
385   end
386
387   def render_controller_partial partial, opts
388     cname = opts.delete :controller_name
389     begin
390       render opts.merge(partial: "#{cname}/#{partial}")
391     rescue ActionView::MissingTemplate
392       render opts.merge(partial: "application/#{partial}")
393     end
394   end
395
396   def fa_icon_class_for_object object
397     case object.class.to_s.to_sym
398     when :User
399       'fa-user'
400     when :Group
401       object.group_class ? 'fa-folder' : 'fa-users'
402     when :Job, :PipelineInstance, :PipelineTemplate
403       'fa-gears'
404     when :Collection
405       'fa-archive'
406     when :Specimen
407       'fa-flask'
408     when :Trait
409       'fa-clipboard'
410     when :Human
411       'fa-male'
412     when :VirtualMachine
413       'fa-terminal'
414     when :Repository
415       'fa-code-fork'
416     when :Link
417       'fa-arrows-h'
418     when :User
419       'fa-user'
420     when :Node
421       'fa-cloud'
422     when :KeepService
423       'fa-exchange'
424     when :KeepDisk
425       'fa-hdd-o'
426     else
427       'fa-cube'
428     end
429   end
430 end