2872: Add "clone and edit" button to pipeline instance page.
[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               link_name = resource_class.find(link_uuid).friendly_link_name
99             rescue RuntimeError
100               # If that lookup failed, the link will too. So don't make one.
101               return attrvalue
102             end
103           end
104         end
105         if opts[:with_class_name]
106           link_name = "#{resource_class.to_s}: #{link_name}"
107         end
108         if !opts[:no_tags] and resource_class == Collection
109           Link.where(head_uuid: link_uuid, link_class: ["tag", "identifier"]).each do |tag|
110             link_name += ' <span class="label label-info">' + html_escape(tag.name) + '</span>'
111           end
112         end
113         if opts[:thumbnail] and resource_class == Collection
114           # add an image thumbnail if the collection consists of a single image file.
115           Collection.where(uuid: link_uuid).each do |c|
116             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
117               link_name += " "
118               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
119             end
120           end
121         end
122       end
123       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
124       if opts[:no_link]
125         raw(link_name)
126       else
127         link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: link_uuid }, style_opts
128       end
129     else
130       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
131       attrvalue
132     end
133   end
134
135   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
136     attrvalue = object.send(attr) if attrvalue.nil?
137     if !object.attribute_editable?(attr, :ever) or
138         (!object.editable? and
139          !object.owner_uuid.in?(my_folders.collect(&:uuid)))
140       return attrvalue 
141     end
142
143     input_type = 'text'
144     case object.class.attribute_info[attr.to_sym].andand[:type]
145     when 'text'
146       input_type = 'textarea'
147     when 'datetime'
148       input_type = 'date'
149     else
150       input_type = 'text'
151     end
152
153     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
154
155     ajax_options = {
156       "data-pk" => {
157         id: object.uuid,
158         key: object.class.to_s.underscore
159       }
160     }
161     if object.uuid
162       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
163     else
164       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
165       ajax_options['data-pk'][:defaults] = object.attributes
166     end
167     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
168     @unique_id ||= (Time.now.to_f*1000000).to_i
169     span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
170
171     span_tag = content_tag 'span', attrvalue.to_s, {
172       "data-emptytext" => (object.andand.default_name || 'none'),
173       "data-placement" => "bottom",
174       "data-type" => input_type,
175       "data-title" => "Edit #{attr.gsub '_', ' '}",
176       "data-name" => attr,
177       "data-object-uuid" => object.uuid,
178       "data-toggle" => "manual",
179       "id" => span_id,
180       :class => "editable"
181     }.merge(htmloptions).merge(ajax_options)
182     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>')
183     if htmloptions[:tipplacement] == :left
184       edit_button + ' ' + span_tag
185     else
186       span_tag + ' ' + edit_button
187     end
188   end
189
190   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
191     datatype = nil
192     required = true
193     attrvalue = value_info
194
195     if value_info.is_a? Hash
196       if value_info[:output_of]
197         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
198       end
199       if value_info[:dataclass]
200         dataclass = value_info[:dataclass]
201       end
202       if value_info[:optional] != nil
203         required = (value_info[:optional] != "true")
204       end
205       if value_info[:required] != nil
206         required = value_info[:required]
207       end
208
209       # Pick a suitable attrvalue to show as the current value (i.e.,
210       # the one that would be used if we ran the pipeline right now).
211       if value_info[:value]
212         attrvalue = value_info[:value]
213       elsif value_info[:default]
214         attrvalue = value_info[:default]
215       else
216         attrvalue = ''
217       end
218     end
219
220     if !object or
221         !object.attribute_editable?(attr, :ever) or
222         (!object.editable? and
223          !object.owner_uuid.in?(my_folders.collect(&:uuid)))
224       return link_to_if_arvados_object attrvalue
225     end
226
227     if dataclass
228       begin
229         dataclass = dataclass.constantize
230       rescue NameError
231       end
232     else
233       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
234     end
235
236     id = "#{object.uuid}-#{subattr.join('-')}"
237     dn = "[#{attr}]"
238     subattr.each do |a|
239       dn += "[#{a}]"
240     end
241     if value_info.is_a? Hash
242       dn += '[value]'
243     end
244
245     if dataclass == Collection
246       selection_param = object.class.to_s.underscore + dn
247       display_value = attrvalue
248       if value_info.is_a?(Hash)
249         if (link = Link.find? value_info[:link_uuid])
250           display_value = link.name
251         elsif value_info[:link_name]
252           display_value = value_info[:link_name]
253         end
254       end
255       modal_path = choose_collections_path \
256       ({ title: 'Choose a dataset:',
257          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
258          action_name: 'OK',
259          action_href: pipeline_instance_path(id: object.uuid),
260          action_method: 'patch',
261          action_data: {
262            merge: true,
263            selection_param: selection_param,
264            success: 'page-refresh'
265          }.to_json,
266         })
267       return content_tag('div', :class => 'input-group') do
268         html = text_field_tag(dn, display_value, :class => 'form-control')
269         html + content_tag('span', :class => 'input-group-btn') do
270           link_to('Choose',
271                   modal_path,
272                   { :class => "btn btn-primary",
273                     :remote => true,
274                     :method => 'get',
275                   })
276         end
277       end
278     end
279
280     if dataclass.andand.is_a?(Class)
281       datatype = 'select'
282     elsif dataclass == 'number'
283       datatype = 'number'
284     elsif attrvalue.is_a? Array
285       # TODO: find a way to edit arrays with x-editable
286       return attrvalue
287     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
288       datatype = 'number'
289     elsif attrvalue.is_a? String
290       datatype = 'text'
291     end
292
293     selectables = []
294     attrtext = attrvalue
295     if dataclass and dataclass.is_a? Class
296       if attrvalue and !attrvalue.empty?
297         Link.where(head_uuid: attrvalue, link_class: ["tag", "identifier"]).each do |tag|
298           attrtext += " [#{tag.name}]"
299         end
300         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
301       end
302       #dataclass.where(uuid: attrvalue).each do |item|
303       #  selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
304       #end
305       itemuuids = []
306       dataclass.limit(10).each do |item|
307         itemuuids << item.uuid
308         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
309       end
310       Link.where(head_uuid: itemuuids, link_class: ["tag", "identifier"]).each do |tag|
311         selectables.each do |selectable|
312           if selectable['uuid'] == tag.head_uuid
313             selectable['name'] += ' [' + tag.name + ']'
314           end
315         end
316       end
317     end
318
319     lt = link_to attrtext, '#', {
320       "data-emptytext" => "none",
321       "data-placement" => "bottom",
322       "data-type" => datatype,
323       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
324       "data-title" => "Set value for #{subattr[-1].to_s}",
325       "data-name" => dn,
326       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
327       "data-showbuttons" => "false",
328       "data-value" => attrvalue,
329       :class => "editable #{'required' if required} form-control",
330       :id => id
331     }.merge(htmloptions)
332
333     lt += raw("\n<script>")
334
335     if selectables.any?
336       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
337     end
338
339     lt += raw("$('[data-name=\"#{dn}\"]').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
340
341     lt += raw("</script>")
342
343     lt
344   end
345
346   def render_arvados_object_list_start(list, button_text, button_href,
347                                        params={}, *rest, &block)
348     show_max = params.delete(:show_max) || 3
349     params[:class] ||= 'btn btn-xs btn-default'
350     list[0...show_max].each { |item| yield item }
351     unless list[show_max].nil?
352       link_to(h(button_text) +
353               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
354               button_href, params, *rest)
355     end
356   end
357
358   def render_controller_partial partial, opts
359     cname = opts.delete :controller_name
360     begin
361       render opts.merge(partial: "#{cname}/#{partial}")
362     rescue ActionView::MissingTemplate
363       render opts.merge(partial: "application/#{partial}")
364     end
365   end
366     
367   def fa_icon_class_for_object object
368     case object.class.to_s.to_sym
369     when :User
370       'fa-user'
371     when :Group
372       object.group_class ? 'fa-folder' : 'fa-users'
373     when :Job, :PipelineInstance, :PipelineTemplate
374       'fa-gears'
375     when :Collection
376       'fa-archive'
377     when :Specimen
378       'fa-flask'
379     when :Trait
380       'fa-clipboard'
381     when :Human
382       'fa-male'
383     when :VirtualMachine
384       'fa-terminal'
385     when :Repository
386       'fa-code-fork'
387     when :Link
388       'fa-arrows-h'
389     when :User
390       'fa-user'
391     when :Node
392       'fa-cloud'
393     when :KeepService
394       'fa-exchange'
395     when :KeepDisk
396       'fa-hdd-o'
397     else
398       'fa-cube'
399     end
400   end
401 end