2871: some more comments
[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       link_uuid = attrvalue.is_a?(ArvadosBase) ? attrvalue.uuid : attrvalue
83       link_name = opts[:link_text]
84       if !link_name
85         link_name = link_uuid
86
87         if opts[:friendly_name]
88           if attrvalue.respond_to? :friendly_link_name
89             link_name = attrvalue.friendly_link_name
90           else
91             begin
92               if resource_class.name == 'Collection'
93                 link_name = collections_for_object(link_uuid).first.friendly_link_name
94               else 
95                 link_name = object_for_dataclass(resource_class, link_uuid).friendly_link_name
96               end
97             rescue RuntimeError
98               # If that lookup failed, the link will too. So don't make one.
99               return attrvalue
100             end
101           end
102         end
103         if opts[:with_class_name]
104           link_name = "#{resource_class.to_s}: #{link_name}"
105         end
106         if !opts[:no_tags] and resource_class == Collection
107           links_for_object(link_uuid).each do |tag|
108             if tag.link_class.in? ["tag", "identifier"]
109               link_name += ' <span class="label label-info">' + html_escape(tag.name) + '</span>'
110             end
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           collections_for_object(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
169     content_tag 'span', attrvalue.to_s, {
170       "data-emptytext" => "none",
171       "data-placement" => "bottom",
172       "data-type" => input_type,
173       "data-title" => "Update #{attr.gsub '_', ' '}",
174       "data-name" => attr,
175       "data-object-uuid" => object.uuid,
176       :class => "editable"
177     }.merge(htmloptions).merge(ajax_options)
178   end
179
180   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
181     datatype = nil
182     required = true
183     attrvalue = value_info
184
185     if value_info.is_a? Hash
186       if value_info[:output_of]
187         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
188       end
189       if value_info[:dataclass]
190         dataclass = value_info[:dataclass]
191       end
192       if value_info[:optional] != nil
193         required = (value_info[:optional] != "true")
194       end
195       if value_info[:required] != nil
196         required = value_info[:required]
197       end
198
199       # Pick a suitable attrvalue to show as the current value (i.e.,
200       # the one that would be used if we ran the pipeline right now).
201       if value_info[:value]
202         attrvalue = value_info[:value]
203       elsif value_info[:default]
204         attrvalue = value_info[:default]
205       else
206         attrvalue = ''
207       end
208     end
209
210     if !object or
211         !object.attribute_editable?(attr, :ever) or
212         (!object.editable? and
213          !object.owner_uuid.in?(my_folders.collect(&:uuid)))
214       return link_to_if_arvados_object attrvalue
215     end
216
217     if dataclass
218       begin
219         dataclass = dataclass.constantize
220       rescue NameError
221       end
222     else
223       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
224     end
225
226     if dataclass.andand.is_a?(Class)
227       datatype = 'select'
228     elsif dataclass == 'number'
229       datatype = 'number'
230     elsif attrvalue.is_a? Array
231       # TODO: find a way to edit arrays with x-editable
232       return attrvalue
233     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
234       datatype = 'number'
235     elsif attrvalue.is_a? String
236       datatype = 'text'
237     end
238
239     id = "#{object.uuid}-#{subattr.join('-')}"
240     dn = "[#{attr}]"
241     subattr.each do |a|
242       dn += "[#{a}]"
243     end
244     if value_info.is_a? Hash
245       dn += '[value]'
246     end
247
248     # preload data
249     preload_uuids = []
250     items = []
251     selectables = []
252
253     attrtext = attrvalue
254     if dataclass and dataclass.is_a? Class
255       objects = get_n_objects_of_class dataclass, 10
256       objects.each do |item|
257         items << item
258         preload_uuids << item.uuid
259       end
260       if attrvalue and !attrvalue.empty?
261         preload_uuids << attrvalue
262       end
263       preload_links_for_objects preload_uuids
264
265       if attrvalue and !attrvalue.empty?
266         links_for_object(attrvalue).each do |link|
267           if link.link_class.in? ["tag", "identifier"]
268             attrtext += " [#{tag.name}]"
269           end
270         end
271         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
272       end
273       itemuuids = []
274       items.each do |item|
275         itemuuids << item.uuid
276         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
277       end
278       
279       itemuuids.each do |itemuuid|
280         links_for_object(itemuuid).each do |link|
281           if link.link_class.in? ["tag", "identifier"]
282             selectables.each do |selectable|
283               if selectable['uuid'] == tag.head_uuid
284                 selectable['name'] += ' [' + tag.name + ']'
285               end
286             end
287           end
288         end
289       end
290     end
291
292     lt = link_to attrtext, '#', {
293       "data-emptytext" => "none",
294       "data-placement" => "bottom",
295       "data-type" => datatype,
296       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
297       "data-title" => "Set value for #{subattr[-1].to_s}",
298       "data-name" => dn,
299       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
300       "data-showbuttons" => "false",
301       "data-value" => attrvalue,
302       :class => "editable #{'required' if required} form-control",
303       :id => id
304     }.merge(htmloptions)
305
306     lt += raw("\n<script>")
307
308     if selectables.any?
309       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
310     end
311
312     lt += raw("$('[data-name=\"#{dn}\"]').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
313
314     lt += raw("</script>")
315
316     lt
317   end
318
319   def render_arvados_object_list_start(list, button_text, button_href,
320                                        params={}, *rest, &block)
321     show_max = params.delete(:show_max) || 3
322     params[:class] ||= 'btn btn-xs btn-default'
323     list[0...show_max].each { |item| yield item }
324     unless list[show_max].nil?
325       link_to(h(button_text) +
326               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
327               button_href, params, *rest)
328     end
329   end
330 end