Merge branch 'master' into 2681-new-inactive-user-notification
[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               link_name = resource_class.find(link_uuid).friendly_link_name
93             rescue RuntimeError
94               # If that lookup failed, the link will too. So don't make one.
95               return attrvalue
96             end
97           end
98         end
99         if opts[:with_class_name]
100           link_name = "#{resource_class.to_s}: #{link_name}"
101         end
102         if !opts[:no_tags] and resource_class == Collection
103           Link.where(head_uuid: link_uuid, link_class: ["tag", "identifier"]).each do |tag|
104             link_name += ' <span class="label label-info">' + html_escape(tag.name) + '</span>'
105           end
106         end
107         if opts[:thumbnail] and resource_class == Collection
108           # add an image thumbnail if the collection consists of a single image file.
109           Collection.where(uuid: link_uuid).each do |c|
110             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
111               link_name += " "
112               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
113             end
114           end
115         end
116       end
117       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
118       if opts[:no_link]
119         raw(link_name)
120       else
121         link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: link_uuid }, style_opts
122       end
123     else
124       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
125       attrvalue
126     end
127   end
128
129   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
130     attrvalue = object.send(attr) if attrvalue.nil?
131     return attrvalue if !object.attribute_editable? attr
132
133     input_type = 'text'
134     case object.class.attribute_info[attr.to_sym].andand[:type]
135     when 'text'
136       input_type = 'textarea'
137     when 'datetime'
138       input_type = 'date'
139     else
140       input_type = 'text'
141     end
142
143     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
144
145     ajax_options = {
146       "data-pk" => {
147         id: object.uuid,
148         key: object.class.to_s.underscore
149       }
150     }
151     if object.uuid
152       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
153     else
154       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
155       ajax_options['data-pk'][:defaults] = object.attributes
156     end
157     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
158
159     content_tag 'span', attrvalue.to_s, {
160       "data-emptytext" => "none",
161       "data-placement" => "bottom",
162       "data-type" => input_type,
163       "data-title" => "Update #{attr.gsub '_', ' '}",
164       "data-name" => attr,
165       "data-object-uuid" => object.uuid,
166       :class => "editable"
167     }.merge(htmloptions).merge(ajax_options)
168   end
169
170   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
171     datatype = nil
172     required = true
173     attrvalue = value_info
174
175     if value_info.is_a? Hash
176       if value_info[:output_of]
177         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
178       end
179       if value_info[:dataclass]
180         dataclass = value_info[:dataclass]
181       end
182       if value_info[:optional] != nil
183         required = (value_info[:optional] != "true")
184       end
185       if value_info[:required] != nil
186         required = value_info[:required]
187       end
188
189       # Pick a suitable attrvalue to show as the current value (i.e.,
190       # the one that would be used if we ran the pipeline right now).
191       if value_info[:value]
192         attrvalue = value_info[:value]
193       elsif value_info[:default]
194         attrvalue = value_info[:default]
195       else
196         attrvalue = ''
197       end
198     end
199
200     unless object.andand.attribute_editable? attr
201       return link_to_if_arvados_object attrvalue
202     end
203
204     if dataclass
205       begin
206         dataclass = dataclass.constantize
207       rescue NameError
208       end
209     else
210       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
211     end
212
213     if dataclass.andand.is_a?(Class)
214       datatype = 'select'
215     elsif dataclass == 'number'
216       datatype = 'number'
217     elsif attrvalue.is_a? Array
218       # TODO: find a way to edit arrays with x-editable
219       return attrvalue
220     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
221       datatype = 'number'
222     elsif attrvalue.is_a? String
223       datatype = 'text'
224     end
225
226     id = "#{object.uuid}-#{subattr.join('-')}"
227     dn = "[#{attr}]"
228     subattr.each do |a|
229       dn += "[#{a}]"
230     end
231     if value_info.is_a? Hash
232       dn += '[value]'
233     end
234
235     selectables = []
236     attrtext = attrvalue
237     if dataclass and dataclass.is_a? Class
238       if attrvalue and !attrvalue.empty?
239         Link.where(head_uuid: attrvalue, link_class: ["tag", "identifier"]).each do |tag|
240           attrtext += " [#{tag.name}]"
241         end
242         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
243       end
244       #dataclass.where(uuid: attrvalue).each do |item|
245       #  selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
246       #end
247       itemuuids = []
248       dataclass.limit(10).each do |item|
249         itemuuids << item.uuid
250         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
251       end
252       Link.where(head_uuid: itemuuids, link_class: ["tag", "identifier"]).each do |tag|
253         selectables.each do |selectable|
254           if selectable['uuid'] == tag.head_uuid
255             selectable['name'] += ' [' + tag.name + ']'
256           end
257         end
258       end
259     end
260
261     lt = link_to attrtext, '#', {
262       "data-emptytext" => "none",
263       "data-placement" => "bottom",
264       "data-type" => datatype,
265       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
266       "data-title" => "Set value for #{subattr[-1].to_s}",
267       "data-name" => dn,
268       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
269       "data-showbuttons" => "false",
270       "data-value" => attrvalue,
271       :class => "editable #{'required' if required} form-control",
272       :id => id
273     }.merge(htmloptions)
274
275     lt += raw("\n<script>")
276
277     if selectables.any?
278       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
279     end
280
281     lt += raw("$('[data-name=\"#{dn}\"]').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
282
283     lt += raw("</script>")
284
285     lt
286   end
287
288   def render_arvados_object_list_start(list, button_text, button_href,
289                                        params={}, *rest, &block)
290     show_max = params.delete(:show_max) || 3
291     params[:class] ||= 'btn btn-xs btn-default'
292     list[0...show_max].each { |item| yield item }
293     unless list[show_max].nil?
294       link_to(h(button_text) +
295               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
296               button_href, params, *rest)
297     end
298   end
299 end