2872: Add job summary partial.
[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     span_tag + 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="edit"><i class="fa fa-fw fa-pencil"></i></a>')
183   end
184
185   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
186     datatype = nil
187     required = true
188     attrvalue = value_info
189
190     if value_info.is_a? Hash
191       if value_info[:output_of]
192         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
193       end
194       if value_info[:dataclass]
195         dataclass = value_info[:dataclass]
196       end
197       if value_info[:optional] != nil
198         required = (value_info[:optional] != "true")
199       end
200       if value_info[:required] != nil
201         required = value_info[:required]
202       end
203
204       # Pick a suitable attrvalue to show as the current value (i.e.,
205       # the one that would be used if we ran the pipeline right now).
206       if value_info[:value]
207         attrvalue = value_info[:value]
208       elsif value_info[:default]
209         attrvalue = value_info[:default]
210       else
211         attrvalue = ''
212       end
213     end
214
215     if !object or
216         !object.attribute_editable?(attr, :ever) or
217         (!object.editable? and
218          !object.owner_uuid.in?(my_folders.collect(&:uuid)))
219       return link_to_if_arvados_object attrvalue
220     end
221
222     if dataclass
223       begin
224         dataclass = dataclass.constantize
225       rescue NameError
226       end
227     else
228       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
229     end
230
231     id = "#{object.uuid}-#{subattr.join('-')}"
232     dn = "[#{attr}]"
233     subattr.each do |a|
234       dn += "[#{a}]"
235     end
236     if value_info.is_a? Hash
237       dn += '[value]'
238     end
239
240     if dataclass == Collection
241       selection_param = object.class.to_s.underscore + dn
242       display_value = attrvalue
243       if value_info.is_a?(Hash)
244         if (link = Link.find? value_info[:link_uuid])
245           display_value = link.name
246         elsif value_info[:link_name]
247           display_value = value_info[:link_name]
248         end
249       end
250       modal_path = choose_collections_path \
251       ({ title: 'Choose a dataset:',
252          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
253          action_name: 'OK',
254          action_href: pipeline_instance_path(id: object.uuid),
255          action_method: 'patch',
256          action_data: {
257            merge: true,
258            selection_param: selection_param,
259            success: 'page-refresh'
260          }.to_json,
261         })
262       return content_tag('div', :class => 'input-group') do
263         html = text_field_tag(dn, display_value, :class => 'form-control')
264         html + content_tag('span', :class => 'input-group-btn') do
265           link_to('Choose',
266                   modal_path,
267                   { :class => "btn btn-primary",
268                     :remote => true,
269                     :method => 'get',
270                   })
271         end
272       end
273     end
274
275     if dataclass.andand.is_a?(Class)
276       datatype = 'select'
277     elsif dataclass == 'number'
278       datatype = 'number'
279     elsif attrvalue.is_a? Array
280       # TODO: find a way to edit arrays with x-editable
281       return attrvalue
282     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
283       datatype = 'number'
284     elsif attrvalue.is_a? String
285       datatype = 'text'
286     end
287
288     selectables = []
289     attrtext = attrvalue
290     if dataclass and dataclass.is_a? Class
291       if attrvalue and !attrvalue.empty?
292         Link.where(head_uuid: attrvalue, link_class: ["tag", "identifier"]).each do |tag|
293           attrtext += " [#{tag.name}]"
294         end
295         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
296       end
297       #dataclass.where(uuid: attrvalue).each do |item|
298       #  selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
299       #end
300       itemuuids = []
301       dataclass.limit(10).each do |item|
302         itemuuids << item.uuid
303         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
304       end
305       Link.where(head_uuid: itemuuids, link_class: ["tag", "identifier"]).each do |tag|
306         selectables.each do |selectable|
307           if selectable['uuid'] == tag.head_uuid
308             selectable['name'] += ' [' + tag.name + ']'
309           end
310         end
311       end
312     end
313
314     lt = link_to attrtext, '#', {
315       "data-emptytext" => "none",
316       "data-placement" => "bottom",
317       "data-type" => datatype,
318       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
319       "data-title" => "Set value for #{subattr[-1].to_s}",
320       "data-name" => dn,
321       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
322       "data-showbuttons" => "false",
323       "data-value" => attrvalue,
324       :class => "editable #{'required' if required} form-control",
325       :id => id
326     }.merge(htmloptions)
327
328     lt += raw("\n<script>")
329
330     if selectables.any?
331       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
332     end
333
334     lt += raw("$('[data-name=\"#{dn}\"]').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
335
336     lt += raw("</script>")
337
338     lt
339   end
340
341   def render_arvados_object_list_start(list, button_text, button_href,
342                                        params={}, *rest, &block)
343     show_max = params.delete(:show_max) || 3
344     params[:class] ||= 'btn btn-xs btn-default'
345     list[0...show_max].each { |item| yield item }
346     unless list[show_max].nil?
347       link_to(h(button_text) +
348               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
349               button_href, params, *rest)
350     end
351   end
352
353   def render_controller_partial partial, opts
354     cname = opts.delete :controller_name
355     begin
356       render opts.merge(partial: "#{cname}/#{partial}")
357     rescue ActionView::MissingTemplate
358       render opts.merge(partial: "application/#{partial}")
359     end
360   end
361     
362   def fa_icon_class_for_object object
363     case object.class.to_s.to_sym
364     when :User
365       'fa-user'
366     when :Group
367       object.group_class ? 'fa-folder' : 'fa-users'
368     when :Job, :PipelineInstance, :PipelineTemplate
369       'fa-gears'
370     when :Collection
371       'fa-archive'
372     when :Specimen
373       'fa-flask'
374     when :Trait
375       'fa-clipboard'
376     when :Human
377       'fa-male'
378     when :VirtualMachine
379       'fa-terminal'
380     when :Repository
381       'fa-code-fork'
382     when :Link
383       'fa-arrows-h'
384     when :User
385       'fa-user'
386     when :Node
387       'fa-cloud'
388     when :KeepService
389       'fa-exchange'
390     when :KeepDisk
391       'fa-hdd-o'
392     else
393       'fa-cube'
394     end
395   end
396 end