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