Merge branch '2640-folder-api' into 1970-folder-view
[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
21     orders = {
22       1 => "bytes",
23       1024 => "KiB",
24       (1024*1024) => "MiB",
25       (1024*1024*1024) => "GiB",
26       (1024*1024*1024*1024) => "TiB"
27     }
28
29     orders.each do |k, v|
30       sig = (n.to_f/k)
31       if sig >=1 and sig < 1024
32         if v == 'bytes'
33           return "%i #{v}" % sig
34         else
35           return "%0.1f #{v}" % sig
36         end
37       end
38     end
39
40     return h(n)
41     #raw = n.to_s
42     #cooked = ''
43     #while raw.length > 3
44     #  cooked = ',' + raw[-3..-1] + cooked
45     #  raw = raw[0..-4]
46     #end
47     #cooked = raw + cooked
48   end
49
50   def resource_class_for_uuid(attrvalue, opts={})
51     ArvadosBase::resource_class_for_uuid(attrvalue, opts)
52   end
53
54   ##
55   # Returns HTML that links to the Arvados object specified in +attrvalue+
56   # Provides various output control and styling options.
57   #
58   # +attrvalue+ an Arvados model object or uuid
59   #
60   # +opts+ a set of flags to control output:
61   #
62   # [:link_text] the link text to use (may include HTML), overrides everything else
63   #
64   # [:friendly_name] whether to use the "friendly" name in the link text (by
65   # calling #friendly_link_name on the object), otherwise use the uuid
66   #
67   # [:with_class_name] prefix the link text with the class name of the model
68   #
69   # [:no_tags] disable tags in the link text (default is to show tags).
70   # Currently tags are only shown for Collections.
71   #
72   # [:thumbnail] if the object is a collection, show an image thumbnail if the
73   # collection consists of a single image file.
74   #
75   # [:no_link] don't create a link, just return the link text
76   #
77   # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
78   #
79   def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
80     if (resource_class = resource_class_for_uuid(attrvalue, opts))
81       link_uuid = attrvalue.is_a?(ArvadosBase) ? attrvalue.uuid : attrvalue
82       link_name = opts[:link_text]
83       if !link_name
84         link_name = link_uuid
85
86         if opts[:friendly_name]
87           if attrvalue.respond_to? :friendly_link_name
88             link_name = attrvalue.friendly_link_name
89           else
90             begin
91               link_name = resource_class.find(link_uuid).friendly_link_name
92             rescue RuntimeError
93               # If that lookup failed, the link will too. So don't make one.
94               return attrvalue
95             end
96           end
97         end
98         if opts[:with_class_name]
99           link_name = "#{resource_class.to_s}: #{link_name}"
100         end
101         if !opts[:no_tags] and resource_class == Collection
102           Link.where(head_uuid: link_uuid, link_class: ["tag", "identifier"]).each do |tag|
103             link_name += ' <span class="label label-info">' + html_escape(tag.name) + '</span>'
104           end
105         end
106         if opts[:thumbnail] and resource_class == Collection
107           # add an image thumbnail if the collection consists of a single image file.
108           Collection.where(uuid: link_uuid).each do |c|
109             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
110               link_name += " "
111               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
112             end
113           end
114         end
115       end
116       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
117       if opts[:no_link]
118         raw(link_name)
119       else
120         link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: link_uuid }, style_opts
121       end
122     else
123       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
124       attrvalue
125     end
126   end
127
128   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
129     attrvalue = object.send(attr) if attrvalue.nil?
130     return attrvalue if !object.attribute_editable? attr
131
132     input_type = 'text'
133     case object.class.attribute_info[attr.to_sym].andand[:type]
134     when 'text'
135       input_type = 'textarea'
136     when 'datetime'
137       input_type = 'date'
138     else
139       input_type = 'text'
140     end
141
142     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
143
144     ajax_options = {
145       "data-pk" => {
146         id: object.uuid,
147         key: object.class.to_s.underscore
148       }
149     }
150     if object.uuid
151       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
152     else
153       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
154       ajax_options['data-pk'][:defaults] = object.attributes
155     end
156     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
157
158     content_tag 'span', attrvalue.to_s, {
159       "data-emptytext" => "none",
160       "data-placement" => "bottom",
161       "data-type" => input_type,
162       "data-title" => "Update #{attr.gsub '_', ' '}",
163       "data-name" => attr,
164       "data-object-uuid" => object.uuid,
165       :class => "editable"
166     }.merge(htmloptions).merge(ajax_options)
167   end
168
169   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
170     datatype = nil
171     required = true
172     attrvalue = value_info
173
174     if value_info.is_a? Hash
175       if value_info[:output_of]
176         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
177       end
178       if value_info[:dataclass]
179         dataclass = value_info[:dataclass]
180       end
181       if value_info[:optional] != nil
182         required = (value_info[:optional] != "true")
183       end
184       if value_info[:required] != nil
185         required = value_info[:required]
186       end
187
188       # Pick a suitable attrvalue to show as the current value (i.e.,
189       # the one that would be used if we ran the pipeline right now).
190       if value_info[:value]
191         attrvalue = value_info[:value]
192       elsif value_info[:default]
193         attrvalue = value_info[:default]
194       else
195         attrvalue = ''
196       end
197     end
198
199     unless object.andand.attribute_editable? attr
200       return link_to_if_arvados_object attrvalue
201     end
202
203     if dataclass
204       begin
205         dataclass = dataclass.constantize
206       rescue NameError
207       end
208     else
209       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
210     end
211
212     if dataclass.andand.is_a?(Class)
213       datatype = 'select'
214     elsif dataclass == 'number'
215       datatype = 'number'
216     elsif attrvalue.is_a? Array
217       # TODO: find a way to edit arrays with x-editable
218       return attrvalue
219     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
220       datatype = 'number'
221     elsif attrvalue.is_a? String
222       datatype = 'text'
223     end
224
225     id = "#{object.uuid}-#{subattr.join('-')}"
226     dn = "[#{attr}]"
227     subattr.each do |a|
228       dn += "[#{a}]"
229     end
230     if value_info.is_a? Hash
231       dn += '[value]'
232     end
233
234     selectables = []
235     attrtext = attrvalue
236     if dataclass and dataclass.is_a? Class
237       if attrvalue and !attrvalue.empty?
238         Link.where(head_uuid: attrvalue, link_class: ["tag", "identifier"]).each do |tag|
239           attrtext += " [#{tag.name}]"
240         end
241         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
242       end
243       #dataclass.where(uuid: attrvalue).each do |item|
244       #  selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
245       #end
246       itemuuids = []
247       dataclass.limit(10).each do |item|
248         itemuuids << item.uuid
249         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
250       end
251       Link.where(head_uuid: itemuuids, link_class: ["tag", "identifier"]).each do |tag|
252         selectables.each do |selectable|
253           if selectable['uuid'] == tag.head_uuid
254             selectable['name'] += ' [' + tag.name + ']'
255           end
256         end
257       end
258     end
259
260     lt = link_to attrtext, '#', {
261       "data-emptytext" => "none",
262       "data-placement" => "bottom",
263       "data-type" => datatype,
264       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
265       "data-title" => "Set value for #{subattr[-1].to_s}",
266       "data-name" => dn,
267       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
268       "data-showbuttons" => "false",
269       "data-value" => attrvalue,
270       :class => "editable #{'required' if required}",
271       :id => id
272     }.merge(htmloptions)
273
274     lt += raw("\n<script>")
275
276     if selectables.any?
277       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
278     end
279
280     lt += raw("$('##{id}').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
281
282     lt += raw("</script>")
283
284     lt
285   end
286 end