Merge branch 'master' into 1969-persistent-switch
[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     link_to attrvalue.to_s, '#', {
145       "data-emptytext" => "none",
146       "data-placement" => "bottom",
147       "data-type" => input_type,
148       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore),
149       "data-title" => "Update #{attr.gsub '_', ' '}",
150       "data-name" => attr,
151       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
152       :class => "editable"
153     }.merge(htmloptions)
154   end
155
156   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
157     datatype = nil
158     required = true
159     attrvalue = value_info
160
161     if value_info.is_a? Hash
162       if value_info[:output_of]
163         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
164       end
165       if value_info[:dataclass]
166         dataclass = value_info[:dataclass]
167       end
168       if value_info[:optional] != nil
169         required = (value_info[:optional] != "true")
170       end
171       if value_info[:required] != nil
172         required = value_info[:required]
173       end
174
175       # Pick a suitable attrvalue to show as the current value (i.e.,
176       # the one that would be used if we ran the pipeline right now).
177       if value_info[:value]
178         attrvalue = value_info[:value]
179       elsif value_info[:default]
180         attrvalue = value_info[:default]
181       else
182         attrvalue = ''
183       end
184     end
185
186     unless object.andand.attribute_editable? attr
187       return link_to_if_arvados_object attrvalue
188     end
189
190     if dataclass
191       begin
192         dataclass = dataclass.constantize
193       rescue NameError
194       end
195     else
196       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
197     end
198
199     if dataclass.andand.is_a?(Class)
200       datatype = 'select'
201     elsif dataclass == 'number'
202       datatype = 'number'
203     elsif attrvalue.is_a? Array
204       # TODO: find a way to edit arrays with x-editable
205       return attrvalue
206     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
207       datatype = 'number'
208     elsif attrvalue.is_a? String
209       datatype = 'text'
210     end
211
212     id = "#{object.uuid}-#{subattr.join('-')}"
213     dn = "[#{attr}]"
214     subattr.each do |a|
215       dn += "[#{a}]"
216     end
217     if value_info.is_a? Hash
218       dn += '[value]'
219     end
220
221     selectables = []
222     attrtext = attrvalue
223     if dataclass and dataclass.is_a? Class
224       if attrvalue and !attrvalue.empty?
225         Link.where(head_uuid: attrvalue, link_class: ["tag", "identifier"]).each do |tag|
226           attrtext += " [#{tag.name}]"
227         end
228         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
229       end
230       #dataclass.where(uuid: attrvalue).each do |item|
231       #  selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
232       #end
233       itemuuids = []
234       dataclass.limit(10).each do |item|
235         itemuuids << item.uuid
236         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
237       end
238       Link.where(head_uuid: itemuuids, link_class: ["tag", "identifier"]).each do |tag|
239         selectables.each do |selectable|
240           if selectable['uuid'] == tag.head_uuid
241             selectable['name'] += ' [' + tag.name + ']'
242           end
243         end
244       end
245     end
246
247     lt = link_to attrtext, '#', {
248       "data-emptytext" => "none",
249       "data-placement" => "bottom",
250       "data-type" => datatype,
251       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
252       "data-title" => "Set value for #{subattr[-1].to_s}",
253       "data-name" => dn,
254       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
255       "data-showbuttons" => "false",
256       "data-value" => attrvalue,
257       :class => "editable #{'required' if required}",
258       :id => id
259     }.merge(htmloptions)
260
261     lt += raw("\n<script>")
262
263     if selectables.any?
264       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
265     end
266
267     lt += raw("$('##{id}').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
268
269     lt += raw("</script>")
270
271     lt
272   end
273 end