[FIX] translatability of addition button label in listview
[odoo/odoo.git] / addons / web / static / src / js / view_form.js
1 openerp.web.form = function (openerp) {
2
3 var _t = openerp.web._t;
4 var QWeb = openerp.web.qweb;
5
6 openerp.web.views.add('form', 'openerp.web.FormView');
7 openerp.web.FormView = openerp.web.View.extend( /** @lends openerp.web.FormView# */{
8     /**
9      * Indicates that this view is not searchable, and thus that no search
10      * view should be displayed (if there is one active).
11      */
12     searchable: false,
13     readonly : false,
14     form_template: "FormView",
15     identifier_prefix: 'formview-',
16     /**
17      * @constructs openerp.web.FormView
18      * @extends openerp.web.View
19      *
20      * @param {openerp.web.Session} session the current openerp session
21      * @param {openerp.web.DataSet} dataset the dataset this view will work with
22      * @param {String} view_id the identifier of the OpenERP view object
23      *
24      * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
25      */
26     init: function(parent, dataset, view_id, options) {
27         this._super(parent);
28         this.set_default_options(options);
29         this.dataset = dataset;
30         this.model = dataset.model;
31         this.view_id = view_id || false;
32         this.fields_view = {};
33         this.widgets = {};
34         this.widgets_counter = 0;
35         this.fields = {};
36         this.fields_order = [];
37         this.datarecord = {};
38         this.show_invalid = true;
39         this.default_focus_field = null;
40         this.default_focus_button = null;
41         this.registry = openerp.web.form.widgets;
42         this.has_been_loaded = $.Deferred();
43         this.$form_header = null;
44         this.translatable_fields = [];
45         _.defaults(this.options, {
46             "not_interactible_on_create": false
47         });
48         this.mutating_lock = $.Deferred();
49         this.initial_mutating_lock = this.mutating_lock;
50         this.on_change_lock = $.Deferred().resolve();
51         this.reload_lock = $.Deferred().resolve();
52     },
53     start: function() {
54         this._super();
55         return this.init_view();
56     },
57     init_view: function() {
58         if (this.embedded_view) {
59             var def = $.Deferred().then(this.on_loaded);
60             var self = this;
61             setTimeout(function() {def.resolve(self.embedded_view);}, 0);
62             return def.promise();
63         } else {
64             var context = new openerp.web.CompoundContext(this.dataset.get_context());
65             return this.rpc("/web/view/load", {
66                 "model": this.model,
67                 "view_id": this.view_id,
68                 "view_type": "form",
69                 toolbar: this.options.sidebar,
70                 context: context
71                 }, this.on_loaded);
72         }
73     },
74     stop: function() {
75         if (this.sidebar) {
76             this.sidebar.attachments.stop();
77             this.sidebar.stop();
78         }
79         _.each(this.widgets, function(w) {
80             w.stop();
81         });
82         this._super();
83     },
84     reposition: function ($e) {
85         this.$element = $e;
86         this.on_loaded();
87     },
88     on_loaded: function(data) {
89         var self = this;
90         if (data) {
91             this.fields_order = [];
92             this.fields_view = data;
93             var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
94
95             this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
96         }
97         this.$element.html(this.rendered);
98         _.each(this.widgets, function(w) {
99             w.start();
100         });
101         this.$form_header = this.$element.find('.oe_form_header:first');
102         this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
103             var action = $(this).data('pager-action');
104             self.on_pager_action(action);
105         });
106
107         this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
108         this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
109
110         if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
111             this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
112             this.sidebar.start();
113             this.sidebar.do_unfold();
114             this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
115             this.sidebar.add_toolbar(this.fields_view.toolbar);
116             this.set_common_sidebar_sections(this.sidebar);
117         }
118         this.has_been_loaded.resolve();
119     },
120     do_show: function () {
121         var promise;
122         if (this.dataset.index === null) {
123             // null index means we should start a new record
124             promise = this.on_button_new();
125         } else {
126             promise = this.dataset.read_index(_.keys(this.fields_view.fields)).pipe(this.on_record_loaded);
127         }
128         this.$element.show();
129         if (this.sidebar) {
130             this.sidebar.$element.show();
131         }
132         return promise;
133     },
134     do_hide: function () {
135         this._super();
136         if (this.sidebar) {
137             this.sidebar.$element.hide();
138         }
139     },
140     on_record_loaded: function(record) {
141         var self = this, set_values = [];
142         if (!record) {
143             throw new Error("Form: No record received");
144         }
145         this.datarecord = record;
146
147         _(this.fields).each(function (field, f) {
148             field.reset();
149             var result = field.set_value(self.datarecord[f] || false);
150             set_values.push(result);
151             $.when(result).then(function() {
152                 field.validate();
153             });
154         });
155         return $.when.apply(null, set_values).then(function() {
156             if (!record.id) {
157                 self.show_invalid = false;
158                 // New record: Second pass in order to trigger the onchanges
159                 // respecting the fields order defined in the view
160                 _.each(self.fields_order, function(field_name) {
161                     if (record[field_name] !== undefined) {
162                         var field = self.fields[field_name];
163                         field.dirty = true;
164                         self.do_onchange(field);
165                     }
166                 });
167             }
168             self.on_form_changed();
169             self.initial_mutating_lock.resolve();
170             self.show_invalid = true;
171             self.do_update_pager(record.id == null);
172             if (self.sidebar) {
173                 self.sidebar.attachments.do_update();
174             }
175             if (self.default_focus_field && !self.embedded_view) {
176                 self.default_focus_field.focus();
177             }
178             if (record.id) {
179                 self.do_push_state({id:record.id});
180             }
181         });
182     },
183     on_form_changed: function() {
184         for (var w in this.widgets) {
185             w = this.widgets[w];
186             w.process_modifiers();
187             w.update_dom();
188         }
189     },
190     on_pager_action: function(action) {
191         if (this.can_be_discarded()) {
192             switch (action) {
193                 case 'first':
194                     this.dataset.index = 0;
195                     break;
196                 case 'previous':
197                     this.dataset.previous();
198                     break;
199                 case 'next':
200                     this.dataset.next();
201                     break;
202                 case 'last':
203                     this.dataset.index = this.dataset.ids.length - 1;
204                     break;
205             }
206             this.reload();
207         }
208     },
209     do_update_pager: function(hide_index) {
210         var $pager = this.$form_header.find('div.oe_form_pager');
211         var index = hide_index ? '-' : this.dataset.index + 1;
212         $pager.find('span.oe_pager_index').html(index);
213         $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
214     },
215     parse_on_change: function (on_change, widget) {
216         var self = this;
217         var onchange = _.str.trim(on_change);
218         var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
219         if (!call) {
220             return null;
221         }
222
223         var method = call[1];
224         if (!_.str.trim(call[2])) {
225             return {method: method, args: [], context_index: null}
226         }
227
228         var argument_replacement = {
229             'False': function () {return false;},
230             'True': function () {return true;},
231             'None': function () {return null;},
232             'context': function (i) {
233                 context_index = i;
234                 var ctx = widget.build_context ? widget.build_context() : {};
235                 return ctx;
236             }
237         };
238         var parent_fields = null, context_index = null;
239         var args = _.map(call[2].split(','), function (a, i) {
240             var field = _.str.trim(a);
241
242             // literal constant or context
243             if (field in argument_replacement) {
244                 return argument_replacement[field](i);
245             }
246             // literal number
247             if (/^-?\d+(\.\d+)?$/.test(field)) {
248                 return Number(field);
249             }
250             // form field
251             if (self.fields[field]) {
252                 var value = self.fields[field].get_on_change_value();
253                 return value == null ? false : value;
254             }
255             // parent field
256             var splitted = field.split('.');
257             if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
258                 if (parent_fields === null) {
259                     parent_fields = self.dataset.parent_view.get_fields_values();
260                 }
261                 var p_val = parent_fields[_.str.trim(splitted[1])];
262                 if (p_val !== undefined) {
263                     return p_val == null ? false : p_val;
264                 }
265             }
266             // string literal
267             var first_char = field[0], last_char = field[field.length-1];
268             if ((first_char === '"' && last_char === '"')
269                 || (first_char === "'" && last_char === "'")) {
270                 return field.slice(1, -1);
271             }
272
273             throw new Error("Could not get field with name '" + field +
274                             "' for onchange '" + onchange + "'");
275         });
276
277         return {
278             method: method,
279             args: args,
280             context_index: context_index
281         };
282     },
283     do_onchange: function(widget, processed) {
284         var self = this;
285         var act = function() {
286             try {
287                 processed = processed || [];
288                 var on_change = widget.node.attrs.on_change;
289                 if (on_change) {
290                     var change_spec = self.parse_on_change(on_change, widget);
291                     if (change_spec) {
292                         var ajax = {
293                             url: '/web/dataset/call',
294                             async: false
295                         };
296                         return self.rpc(ajax, {
297                             model: self.dataset.model,
298                             method: change_spec.method,
299                             args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
300                             context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
301                         }).pipe(function(response) {
302                             return self.on_processed_onchange(response, processed);
303                         });
304                     } else {
305                         console.warn("Wrong on_change format", on_change);
306                     }
307                 }
308             } catch(e) {
309                 console.error(e);
310                 return $.Deferred().reject();
311             }
312         };
313         this.on_change_lock = this.on_change_lock.pipe(act, act);
314         return this.on_change_lock;
315     },
316     on_processed_onchange: function(response, processed) {
317         try {
318         var result = response;
319         if (result.value) {
320             for (var f in result.value) {
321                 var field = this.fields[f];
322                 // If field is not defined in the view, just ignore it
323                 if (field) {
324                     var value = result.value[f];
325                     processed.push(field.name);
326                     if (field.get_value() != value) {
327                         field.set_value(value);
328                         field.dirty = true;
329                         if (_.indexOf(processed, field.name) < 0) {
330                             this.do_onchange(field, processed);
331                         }
332                     }
333                 }
334             }
335             this.on_form_changed();
336         }
337         if (!_.isEmpty(result.warning)) {
338             $(QWeb.render("DialogWarning", result.warning)).dialog({
339                 modal: true,
340                 buttons: {
341                     Ok: function() {
342                         $(this).dialog("close");
343                     }
344                 }
345             });
346         }
347         if (result.domain) {
348             // TODO:
349         }
350         return $.Deferred().resolve();
351         } catch(e) {
352             console.error(e);
353             return $.Deferred().reject();
354         }
355     },
356     on_button_save: function() {
357         var self = this;
358         return this.do_save().then(function(result) {
359             self.do_prev_view(result.created);
360         });
361     },
362     on_button_cancel: function() {
363         return this.do_prev_view();
364     },
365     on_button_new: function() {
366         var self = this;
367         var def = $.Deferred();
368         $.when(this.has_been_loaded).then(function() {
369             if (self.can_be_discarded()) {
370                 var keys = _.keys(self.fields_view.fields);
371                 if (keys.length) {
372                     self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
373                         def.resolve();
374                     });
375                 } else {
376                     self.on_record_loaded({}).then(function() {
377                         def.resolve();
378                     });
379                 }
380             }
381         });
382         return def.promise();
383     },
384     can_be_discarded: function() {
385         return true; // FIXME: Disabled until the page view and button refactoring is done
386         return !this.is_dirty() || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
387     },
388     /**
389      * Triggers saving the form's record. Chooses between creating a new
390      * record or saving an existing one depending on whether the record
391      * already has an id property.
392      *
393      * @param {Function} success callback on save success
394      * @param {Boolean} [prepend_on_create=false] if ``do_save`` creates a new record, should that record be inserted at the start of the dataset (by default, records are added at the end)
395      */
396     do_save: function(success, prepend_on_create) {
397         var self = this;
398         var action = function() {
399             try {
400             if (!self.initial_mutating_lock.isResolved() && !self.initial_mutating_lock.isRejected())
401                 return;
402             var form_invalid = false,
403                 values = {},
404                 first_invalid_field = null;
405             for (var f in self.fields) {
406                 f = self.fields[f];
407                 if (!f.is_valid()) {
408                     form_invalid = true;
409                     f.update_dom();
410                     if (!first_invalid_field) {
411                         first_invalid_field = f;
412                     }
413                 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
414                     // Special case 'id' field, do not save this field
415                     // on 'create' : save all non readonly fields
416                     // on 'edit' : save non readonly modified fields
417                     values[f.name] = f.get_value();
418                 }
419             }
420             if (form_invalid) {
421                 first_invalid_field.focus();
422                 self.on_invalid();
423                 return $.Deferred().reject();
424             } else {
425                 var save_deferral;
426                 if (!self.datarecord.id) {
427                     openerp.log("FormView(", self, ") : About to create", values);
428                     save_deferral = self.dataset.create(values).pipe(function(r) {
429                         return self.on_created(r, undefined, prepend_on_create);
430                     }, null);
431                 } else if (_.isEmpty(values)) {
432                     openerp.log("FormView(", self, ") : Nothing to save");
433                     save_deferral = $.Deferred().resolve({}).promise();
434                 } else {
435                     openerp.log("FormView(", self, ") : About to save", values);
436                     save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
437                         return self.on_saved(r);
438                     }, null);
439                 }
440                 return save_deferral.then(success);
441             }
442             } catch (e) {
443                 console.error(e);
444                 return $.Deferred().reject();
445             }
446         };
447         this.mutating_lock = this.mutating_lock.pipe(action, action);
448         return this.mutating_lock;
449     },
450     on_invalid: function() {
451         var msg = "<ul>";
452         _.each(this.fields, function(f) {
453             if (!f.is_valid()) {
454                 msg += "<li>" + f.string + "</li>";
455             }
456         });
457         msg += "</ul>";
458         this.do_warn("The following fields are invalid :", msg);
459     },
460     on_saved: function(r, success) {
461         if (!r.result) {
462             // should not happen in the server, but may happen for internal purpose
463             return $.Deferred().reject();
464         } else {
465             return $.when(this.reload()).pipe(function () {
466                 return $.when(r).then(success); }, null);
467         }
468     },
469     /**
470      * Updates the form' dataset to contain the new record:
471      *
472      * * Adds the newly created record to the current dataset (at the end by
473      *   default)
474      * * Selects that record (sets the dataset's index to point to the new
475      *   record's id).
476      * * Updates the pager and sidebar displays
477      *
478      * @param {Object} r
479      * @param {Function} success callback to execute after having updated the dataset
480      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
481      */
482     on_created: function(r, success, prepend_on_create) {
483         if (!r.result) {
484             // should not happen in the server, but may happen for internal purpose
485             return $.Deferred().reject();
486         } else {
487             this.datarecord.id = r.result;
488             if (!prepend_on_create) {
489                 this.dataset.ids.push(this.datarecord.id);
490                 this.dataset.index = this.dataset.ids.length - 1;
491             } else {
492                 this.dataset.ids.unshift(this.datarecord.id);
493                 this.dataset.index = 0;
494             }
495             this.do_update_pager();
496             if (this.sidebar) {
497                 this.sidebar.attachments.do_update();
498             }
499             openerp.log("The record has been created with id #" + this.datarecord.id);
500             this.reload();
501             return $.when(_.extend(r, {created: true})).then(success);
502         }
503     },
504     on_action: function (action) {
505         console.debug('Executing action', action);
506     },
507     reload: function() {
508         var self = this;
509         var act = function() {
510             if (self.dataset.index == null || self.dataset.index < 0) {
511                 return $.when(self.on_button_new());
512             } else {
513                 return self.dataset.read_index(_.keys(self.fields_view.fields)).pipe(self.on_record_loaded);
514             }
515         };
516         this.reload_lock = this.reload_lock.pipe(act, act);
517         return this.reload_lock;
518     },
519     get_fields_values: function() {
520         var values = {};
521         _.each(this.fields, function(value, key) {
522             var val = value.get_value();
523             values[key] = val;
524         });
525         return values;
526     },
527     get_selected_ids: function() {
528         var id = this.dataset.ids[this.dataset.index];
529         return id ? [id] : [];
530     },
531     recursive_save: function() {
532         var self = this;
533         return $.when(this.do_save()).pipe(function(res) {
534             if (self.dataset.parent_view)
535                 return self.dataset.parent_view.recursive_save();
536         });
537     },
538     is_dirty: function() {
539         return _.any(this.fields, function (value) {
540             return value.is_dirty();
541         });
542     },
543     is_interactible_record: function() {
544         var id = this.datarecord.id;
545         if (!id) {
546             if (this.options.not_interactible_on_create)
547                 return false;
548         } else if (typeof(id) === "string") {
549             if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
550                 return false;
551         }
552         return true;
553     },
554     sidebar_context: function () {
555         return this.do_save().pipe($.proxy(this, 'get_fields_values'));
556     }
557 });
558 openerp.web.FormDialog = openerp.web.Dialog.extend({
559     init: function(parent, options, view_id, dataset) {
560         this._super(parent, options);
561         this.dataset = dataset;
562         this.view_id = view_id;
563         return this;
564     },
565     start: function() {
566         this._super();
567         this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
568             sidebar: false,
569             pager: false
570         });
571         this.form.appendTo(this.$element);
572         this.form.on_created.add_last(this.on_form_dialog_saved);
573         this.form.on_saved.add_last(this.on_form_dialog_saved);
574         return this;
575     },
576     select_id: function(id) {
577         if (this.form.dataset.select_id(id)) {
578             return this.form.do_show();
579         } else {
580             this.do_warn("Could not find id in dataset");
581             return $.Deferred().reject();
582         }
583     },
584     on_form_dialog_saved: function(r) {
585         this.close();
586     }
587 });
588
589 /** @namespace */
590 openerp.web.form = {};
591
592 openerp.web.form.SidebarAttachments = openerp.web.Widget.extend({
593     init: function(parent, form_view) {
594         var $section = parent.add_section(_t('Attachments'), 'attachments');
595         this.$div = $('<div class="oe-sidebar-attachments"></div>');
596         $section.append(this.$div);
597
598         this._super(parent, $section.attr('id'));
599         this.view = form_view;
600     },
601     do_update: function() {
602         if (!this.view.datarecord.id) {
603             this.on_attachments_loaded([]);
604         } else {
605             (new openerp.web.DataSetSearch(
606                 this, 'ir.attachment', this.view.dataset.get_context(),
607                 [
608                     ['res_model', '=', this.view.dataset.model],
609                     ['res_id', '=', this.view.datarecord.id],
610                     ['type', 'in', ['binary', 'url']]
611                 ])).read_slice(['name', 'url', 'type'], {}, this.on_attachments_loaded);
612         }
613     },
614     on_attachments_loaded: function(attachments) {
615         this.attachments = attachments;
616         this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
617         this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
618         this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
619     },
620     on_attachment_changed: function(e) {
621         window[this.element_id + '_iframe'] = this.do_update;
622         var $e = $(e.target);
623         if ($e.val() != '') {
624             this.$element.find('form.oe-binary-form').submit();
625             $e.parent().find('input[type=file]').prop('disabled', true);
626             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
627         }
628     },
629     on_attachment_delete: function(e) {
630         var self = this, $e = $(e.currentTarget);
631         var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
632         if (confirm(_.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
633             this.rpc('/web/dataset/unlink', {
634                 model: 'ir.attachment',
635                 ids: [parseInt($e.attr('data-id'))]
636             }, function(r) {
637                 $e.parent().remove();
638                 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
639             });
640         }
641     }
642 });
643
644 openerp.web.form.compute_domain = function(expr, fields) {
645     var stack = [];
646     for (var i = expr.length - 1; i >= 0; i--) {
647         var ex = expr[i];
648         if (ex.length == 1) {
649             var top = stack.pop();
650             switch (ex) {
651                 case '|':
652                     stack.push(stack.pop() || top);
653                     continue;
654                 case '&':
655                     stack.push(stack.pop() && top);
656                     continue;
657                 case '!':
658                     stack.push(!top);
659                     continue;
660                 default:
661                     throw new Error('Unknown domain operator ' + ex);
662             }
663         }
664
665         var field = fields[ex[0]];
666         if (!field) {
667             throw new Error("Domain references unknown field : " + ex[0]);
668         }
669         var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
670         var op = ex[1];
671         var val = ex[2];
672
673         switch (op.toLowerCase()) {
674             case '=':
675             case '==':
676                 stack.push(field_value == val);
677                 break;
678             case '!=':
679             case '<>':
680                 stack.push(field_value != val);
681                 break;
682             case '<':
683                 stack.push(field_value < val);
684                 break;
685             case '>':
686                 stack.push(field_value > val);
687                 break;
688             case '<=':
689                 stack.push(field_value <= val);
690                 break;
691             case '>=':
692                 stack.push(field_value >= val);
693                 break;
694             case 'in':
695                 stack.push(_(val).contains(field_value));
696                 break;
697             case 'not in':
698                 stack.push(!_(val).contains(field_value));
699                 break;
700             default:
701                 console.warn("Unsupported operator in modifiers :", op);
702         }
703     }
704     return _.all(stack, _.identity);
705 };
706
707 openerp.web.form.Widget = openerp.web.Widget.extend(/** @lends openerp.web.form.Widget# */{
708     template: 'Widget',
709     identifier_prefix: 'formview-widget-',
710     /**
711      * @constructs openerp.web.form.Widget
712      * @extends openerp.web.Widget
713      *
714      * @param view
715      * @param node
716      */
717     init: function(view, node) {
718         this.view = view;
719         this.node = node;
720         this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
721         this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
722         this.type = this.type || node.tag;
723         this.element_name = this.element_name || this.type;
724         this.element_class = [
725             'formview', this.view.view_id, this.element_name,
726             this.view.widgets_counter++].join("_");
727
728         this._super(view);
729
730         this.view.widgets[this.element_class] = this;
731         this.children = node.children;
732         this.colspan = parseInt(node.attrs.colspan || 1, 10);
733         this.decrease_max_width = 0;
734
735         this.string = this.string || node.attrs.string;
736         this.help = this.help || node.attrs.help;
737         this.invisible = this.modifiers['invisible'] === true;
738         this.classname = 'oe_form_' + this.type;
739
740         this.align = parseFloat(this.node.attrs.align);
741         if (isNaN(this.align) || this.align === 1) {
742             this.align = 'right';
743         } else if (this.align === 0) {
744             this.align = 'left';
745         } else {
746             this.align = 'center';
747         }
748
749
750         this.width = this.node.attrs.width;
751     },
752     start: function() {
753         this.$element = this.view.$element.find(
754             '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
755     },
756     process_modifiers: function() {
757         var compute_domain = openerp.web.form.compute_domain;
758         for (var a in this.modifiers) {
759             this[a] = compute_domain(this.modifiers[a], this.view.fields);
760         }
761     },
762     update_dom: function() {
763         this.$element.toggle(!this.invisible);
764     },
765     render: function() {
766         var template = this.template;
767         return QWeb.render(template, { "widget": this });
768     },
769     do_attach_tooltip: function(widget, trigger, options) {
770         widget = widget || this;
771         trigger = trigger || this.$element;
772         options = _.extend({
773                 delay: 1000,
774                 maxWidth: openerp.connection.debug ? '300px' : '200px',
775                 content: function() {
776                     var template = widget.template + '.tooltip';
777                     if (!QWeb.has_template(template)) {
778                         template = 'WidgetLabel.tooltip';
779                     }
780                     return QWeb.render(template, {
781                         debug: openerp.connection.debug,
782                         widget: widget
783                     });
784                 }
785             }, options || {});
786         trigger.tipTip(options);
787     },
788     _build_view_fields_values: function() {
789         var a_dataset = this.view.dataset;
790         var fields_values = this.view.get_fields_values();
791         var active_id = a_dataset.ids[a_dataset.index];
792         _.extend(fields_values, {
793             active_id: active_id || false,
794             active_ids: active_id ? [active_id] : [],
795             active_model: a_dataset.model,
796             parent: a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {}
797         });
798         return fields_values;
799     },
800     _build_eval_context: function() {
801         var a_dataset = this.view.dataset;
802         return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values());
803     },
804     /**
805      * Builds a new context usable for operations related to fields by merging
806      * the fields'context with the action's context.
807      */
808     build_context: function() {
809         var f_context = (this.field || {}).context || {};
810         if (!!f_context.__ref) {
811             var fields_values = this._build_eval_context();
812             f_context = new openerp.web.CompoundDomain(f_context).set_eval_context(fields_values);
813         }
814         // maybe the default_get should only be used when we do a default_get?
815         var v_contexts = _.compact([this.node.attrs.default_get || null,
816             this.node.attrs.context || null]);
817         var v_context = new openerp.web.CompoundContext();
818         _.each(v_contexts, function(x) {v_context.add(x);});
819         if (_.detect(v_contexts, function(x) {return !!x.__ref;})) {
820             var fields_values = this._build_eval_context();
821             v_context.set_eval_context(fields_values);
822         }
823         // if there is a context on the node, overrides the model's context
824         var ctx = v_contexts.length > 0 ? v_context : f_context;
825         return ctx;
826     },
827     build_domain: function() {
828         var f_domain = this.field.domain || [];
829         var n_domain = this.node.attrs.domain || null;
830         // if there is a domain on the node, overrides the model's domain
831         var final_domain = n_domain !== null ? n_domain : f_domain;
832         if (!(final_domain instanceof Array)) {
833             var fields_values = this._build_eval_context();
834             final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
835         }
836         return final_domain;
837     }
838 });
839
840 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
841     template: 'WidgetFrame',
842     init: function(view, node) {
843         this._super(view, node);
844         this.columns = parseInt(node.attrs.col || 4, 10);
845         this.x = 0;
846         this.y = 0;
847         this.table = [];
848         this.add_row();
849         for (var i = 0; i < node.children.length; i++) {
850             var n = node.children[i];
851             if (n.tag == "newline") {
852                 this.add_row();
853             } else {
854                 this.handle_node(n);
855             }
856         }
857         this.set_row_cells_with(this.table[this.table.length - 1]);
858     },
859     add_row: function(){
860         if (this.table.length) {
861             this.set_row_cells_with(this.table[this.table.length - 1]);
862         }
863         var row = [];
864         this.table.push(row);
865         this.x = 0;
866         this.y += 1;
867         return row;
868     },
869     set_row_cells_with: function(row) {
870         var bypass = 0,
871             max_width = 100,
872             row_length = row.length;
873         for (var i = 0; i < row.length; i++) {
874             if (row[i].always_invisible) {
875                 row_length--;
876             } else {
877                 bypass += row[i].width === undefined ? 0 : 1;
878                 max_width -= row[i].decrease_max_width;
879             }
880         }
881         var size_unit = Math.round(max_width / (this.columns - bypass)),
882             colspan_sum = 0;
883         for (var i = 0; i < row.length; i++) {
884             var w = row[i];
885             if (w.always_invisible) {
886                 continue;
887             }
888             colspan_sum += w.colspan;
889             if (w.width === undefined) {
890                 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
891                 max_width -= width;
892                 w.width = width + '%';
893             }
894         }
895     },
896     handle_node: function(node) {
897         var type = {};
898         if (node.tag == 'field') {
899             type = this.view.fields_view.fields[node.attrs.name] || {};
900             if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
901                 // This way we can retain backward compatibility between addons and old clients
902                 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
903                 node.attrs.nolabel = '1';
904             }
905         }
906         var widget = new (this.view.registry.get_any(
907                 [node.attrs.widget, type.type, node.tag])) (this.view, node);
908         if (node.tag == 'field') {
909             if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
910                 this.view.default_focus_field = widget;
911             }
912             if (node.attrs.nolabel != '1') {
913                 var label = new (this.view.registry.get_object('label')) (this.view, node);
914                 label["for"] = widget;
915                 this.add_widget(label, widget.colspan + 1);
916             }
917         }
918         this.add_widget(widget);
919     },
920     add_widget: function(widget, colspan) {
921         var current_row = this.table[this.table.length - 1];
922         if (!widget.always_invisible) {
923             colspan = colspan || widget.colspan;
924             if (current_row.length && (this.x + colspan) > this.columns) {
925                 current_row = this.add_row();
926             }
927             this.x += widget.colspan;
928         }
929         current_row.push(widget);
930         return widget;
931     }
932 });
933
934 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
935     template: 'WidgetGroup'
936 }),
937
938 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
939     template: 'WidgetNotebook',
940     init: function(view, node) {
941         this._super(view, node);
942         this.pages = [];
943         for (var i = 0; i < node.children.length; i++) {
944             var n = node.children[i];
945             if (n.tag == "page") {
946                 var page = new (this.view.registry.get_object('notebookpage'))(
947                         this.view, n, this, this.pages.length);
948                 this.pages.push(page);
949             }
950         }
951     },
952     start: function() {
953         var self = this;
954         this._super.apply(this, arguments);
955         this.$element.find('> ul > li').each(function (index, tab_li) {
956             var page = self.pages[index],
957                 id = _.uniqueId(self.element_name + '-');
958             page.element_id = id;
959             $(tab_li).find('a').attr('href', '#' + id);
960         });
961         this.$element.find('> div').each(function (index, page) {
962             page.id = self.pages[index].element_id;
963         });
964         this.$element.tabs();
965         this.view.on_button_new.add_first(this.do_select_first_visible_tab);
966         if (openerp.connection.debug) {
967             this.do_attach_tooltip(this, this.$element.find('ul:first'), {
968                 defaultPosition: 'top'
969             });
970         }
971     },
972     do_select_first_visible_tab: function() {
973         for (var i = 0; i < this.pages.length; i++) {
974             var page = this.pages[i];
975             if (page.invisible === false) {
976                 this.$element.tabs('select', page.index);
977                 break;
978             }
979         }
980     }
981 });
982
983 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
984     template: 'WidgetNotebookPage',
985     init: function(view, node, notebook, index) {
986         this.notebook = notebook;
987         this.index = index;
988         this.element_name = 'page_' + index;
989         this._super(view, node);
990     },
991     start: function() {
992         this._super.apply(this, arguments);
993         this.$element_tab = this.notebook.$element.find(
994                 '> ul > li:eq(' + this.index + ')');
995     },
996     update_dom: function() {
997         if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
998             this.notebook.do_select_first_visible_tab();
999         }
1000         this.$element_tab.toggle(!this.invisible);
1001         this.$element.toggle(!this.invisible);
1002     }
1003 });
1004
1005 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1006     template: 'WidgetSeparator',
1007     init: function(view, node) {
1008         this._super(view, node);
1009         this.orientation = node.attrs.orientation || 'horizontal';
1010         if (this.orientation === 'vertical') {
1011             this.width = '1';
1012         }
1013         this.classname += '_' + this.orientation;
1014     }
1015 });
1016
1017 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1018     template: 'WidgetButton',
1019     init: function(view, node) {
1020         this._super(view, node);
1021         this.force_disabled = false;
1022         if (this.string) {
1023             // We don't have button key bindings in the webclient
1024             this.string = this.string.replace(/_/g, '');
1025         }
1026         if (node.attrs.default_focus == '1') {
1027             // TODO fme: provide enter key binding to widgets
1028             this.view.default_focus_button = this;
1029         }
1030     },
1031     start: function() {
1032         this._super.apply(this, arguments);
1033         this.$element.find("button").click(this.on_click);
1034         if (this.help || openerp.connection.debug) {
1035             this.do_attach_tooltip();
1036         }
1037     },
1038     on_click: function() {
1039         var self = this;
1040         this.force_disabled = true;
1041         this.check_disable();
1042         this.execute_action().always(function() {
1043             self.force_disabled = false;
1044             self.check_disable();
1045             $.tipTipClear();
1046         });
1047     },
1048     execute_action: function() {
1049         var self = this;
1050         var exec_action = function() {
1051             if (self.node.attrs.confirm) {
1052                 var def = $.Deferred();
1053                 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1054                     title: _t('Confirm'),
1055                     modal: true,
1056                     buttons: {
1057                         Ok: function() {
1058                             self.on_confirmed().then(function() {
1059                                 def.resolve();
1060                             });
1061                             $(this).dialog("close");
1062                         },
1063                         Cancel: function() {
1064                             def.resolve();
1065                             $(this).dialog("close");
1066                         }
1067                     }
1068                 });
1069                 return def.promise();
1070             } else {
1071                 return self.on_confirmed();
1072             }
1073         };
1074         if (!this.node.attrs.special) {
1075             return this.view.recursive_save().pipe(exec_action);
1076         } else {
1077             return exec_action();
1078         }
1079     },
1080     on_confirmed: function() {
1081         var self = this;
1082
1083         var context = this.node.attrs.context;
1084         if (context && context.__ref) {
1085             context = new openerp.web.CompoundContext(context);
1086             context.set_eval_context(this._build_eval_context());
1087         }
1088
1089         return this.view.do_execute_action(
1090             _.extend({}, this.node.attrs, {context: context}),
1091             this.view.dataset, this.view.datarecord.id, function () {
1092                 self.view.reload();
1093             });
1094     },
1095     update_dom: function() {
1096         this._super();
1097         this.check_disable();
1098     },
1099     check_disable: function() {
1100         var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1101         this.$element.find('button').prop('disabled', disabled);
1102         this.$element.find("button").css('color', disabled ? 'grey' : '');
1103     }
1104 });
1105
1106 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1107     template: 'WidgetLabel',
1108     init: function(view, node) {
1109         this.element_name = 'label_' + node.attrs.name;
1110
1111         this._super(view, node);
1112
1113         if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1114             this.template = "WidgetParagraph";
1115             this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1116             // Widgets default to right-aligned, but paragraph defaults to
1117             // left-aligned
1118             if (isNaN(parseFloat(this.node.attrs.align))) {
1119                 this.align = 'left';
1120             }
1121         } else {
1122             this.colspan = 1;
1123             this.width = '1%';
1124             this.decrease_max_width = 1;
1125             this.nowrap = true;
1126         }
1127     },
1128     render: function () {
1129         if (this['for'] && this.type !== 'label') {
1130             return QWeb.render(this.template, {widget: this['for']});
1131         }
1132         // Actual label widgets should not have a false and have type label
1133         return QWeb.render(this.template, {widget: this});
1134     },
1135     start: function() {
1136         this._super();
1137         var self = this;
1138         if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1139             this.do_attach_tooltip(self['for']);
1140         }
1141         this.$element.find("label").dblclick(function() {
1142             var widget = self['for'] || self;
1143             openerp.log(widget.element_class , widget);
1144             window.w = widget;
1145         });
1146     }
1147 });
1148
1149 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1150     /**
1151      * @constructs openerp.web.form.Field
1152      * @extends openerp.web.form.Widget
1153      *
1154      * @param view
1155      * @param node
1156      */
1157     init: function(view, node) {
1158         this.name = node.attrs.name;
1159         this.value = undefined;
1160         view.fields[this.name] = this;
1161         view.fields_order.push(this.name);
1162         this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1163         this.element_name = "field_" + this.name + "_" + this.type;
1164
1165         this._super(view, node);
1166
1167         if (node.attrs.nolabel != '1' && this.colspan > 1) {
1168             this.colspan--;
1169         }
1170         this.field = view.fields_view.fields[node.attrs.name] || {};
1171         this.string = node.attrs.string || this.field.string;
1172         this.help = node.attrs.help || this.field.help;
1173         this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1174         this.readonly = this.modifiers['readonly'] === true;
1175         this.required = this.modifiers['required'] === true;
1176         this.invalid = this.dirty = false;
1177
1178         this.classname = 'oe_form_field_' + this.type;
1179     },
1180     start: function() {
1181         this._super.apply(this, arguments);
1182         if (this.field.translate) {
1183             this.view.translatable_fields.push(this);
1184             this.$element.find('.oe_field_translate').click(this.on_translate);
1185         }
1186         if (this.nolabel && openerp.connection.debug) {
1187             this.do_attach_tooltip(this, this.$element, {
1188                 defaultPosition: 'top'
1189             });
1190         }
1191     },
1192     set_value: function(value) {
1193         this.value = value;
1194         this.invalid = false;
1195         this.update_dom();
1196         this.on_value_changed();
1197     },
1198     set_value_from_ui: function() {
1199         this.on_value_changed();
1200     },
1201     on_value_changed: function() {
1202     },
1203     on_translate: function() {
1204         this.view.open_translate_dialog(this);
1205     },
1206     get_value: function() {
1207         return this.value;
1208     },
1209     is_valid: function() {
1210         return !this.invalid;
1211     },
1212     is_dirty: function() {
1213         return this.dirty && !this.readonly;
1214     },
1215     get_on_change_value: function() {
1216         return this.get_value();
1217     },
1218     update_dom: function() {
1219         this._super.apply(this, arguments);
1220         if (this.field.translate) {
1221             this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1222         }
1223         if (!this.disable_utility_classes) {
1224             this.$element.toggleClass('disabled', this.readonly);
1225             this.$element.toggleClass('required', this.required);
1226             if (this.view.show_invalid) {
1227                 this.$element.toggleClass('invalid', !this.is_valid());
1228             }
1229         }
1230     },
1231     on_ui_change: function() {
1232         this.dirty = true;
1233         this.validate();
1234         if (this.is_valid()) {
1235             this.set_value_from_ui();
1236             this.view.do_onchange(this);
1237             this.view.on_form_changed();
1238         } else {
1239             this.update_dom();
1240         }
1241     },
1242     validate: function() {
1243         this.invalid = false;
1244     },
1245     focus: function() {
1246     },
1247     reset: function() {
1248         this.dirty = false;
1249     }
1250 });
1251
1252 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1253     template: 'FieldChar',
1254     init: function (view, node) {
1255         this._super(view, node);
1256         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1257     },
1258     start: function() {
1259         this._super.apply(this, arguments);
1260         this.$element.find('input').change(this.on_ui_change);
1261     },
1262     set_value: function(value) {
1263         this._super.apply(this, arguments);
1264         var show_value = openerp.web.format_value(value, this, '');
1265         this.$element.find('input').val(show_value);
1266         return show_value;
1267     },
1268     update_dom: function() {
1269         this._super.apply(this, arguments);
1270         this.$element.find('input').prop('disabled', this.readonly);
1271     },
1272     set_value_from_ui: function() {
1273         this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1274         this._super();
1275     },
1276     validate: function() {
1277         this.invalid = false;
1278         try {
1279             var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1280             this.invalid = this.required && value === '';
1281         } catch(e) {
1282             this.invalid = true;
1283         }
1284     },
1285     focus: function() {
1286         this.$element.find('input').focus();
1287     }
1288 });
1289
1290 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1291     template: 'FieldEmail',
1292     start: function() {
1293         this._super.apply(this, arguments);
1294         this.$element.find('button').click(this.on_button_clicked);
1295     },
1296     on_button_clicked: function() {
1297         if (!this.value || !this.is_valid()) {
1298             this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1299         } else {
1300             location.href = 'mailto:' + this.value;
1301         }
1302     }
1303 });
1304
1305 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1306     template: 'FieldUrl',
1307     start: function() {
1308         this._super.apply(this, arguments);
1309         this.$element.find('button').click(this.on_button_clicked);
1310     },
1311     on_button_clicked: function() {
1312         if (!this.value) {
1313             this.do_warn("Resource error", "This resource is empty");
1314         } else {
1315             window.open(this.value);
1316         }
1317     }
1318 });
1319
1320 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1321     init: function (view, node) {
1322         this._super(view, node);
1323         if (node.attrs.digits) {
1324             this.parse_digits(node.attrs.digits);
1325         } else {
1326             this.digits = view.fields_view.fields[node.attrs.name].digits;
1327         }
1328     },
1329     parse_digits: function (digits_attr) {
1330         // could use a Python parser instead.
1331         var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1332         return [parseInt(match[1], 10), parseInt(match[2], 10)];
1333     },
1334     set_value: function(value) {
1335         if (value === false || value === undefined) {
1336             // As in GTK client, floats default to 0
1337             value = 0;
1338         }
1339         this._super.apply(this, [value]);
1340     }
1341 });
1342
1343 openerp.web.DateTimeWidget = openerp.web.Widget.extend({
1344     template: "web.datetimepicker",
1345     jqueryui_object: 'datetimepicker',
1346     type_of_date: "datetime",
1347     init: function(parent) {
1348         this._super(parent);
1349         this.name = parent.name;
1350     },
1351     start: function() {
1352         var self = this;
1353         this.$input = this.$element.find('input.oe_datepicker_master');
1354         this.$input_picker = this.$element.find('input.oe_datepicker_container');
1355         this.$input.change(this.on_change);
1356         this.picker({
1357             onSelect: this.on_picker_select,
1358             changeMonth: true,
1359             changeYear: true,
1360             showWeek: true,
1361             showButtonPanel: true
1362         });
1363         this.$element.find('img.oe_datepicker_trigger').click(function() {
1364             if (!self.readonly) {
1365                 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1366                 self.$input_picker.show();
1367                 self.picker('show');
1368                 self.$input_picker.hide();
1369             }
1370         });
1371         this.set_readonly(false);
1372         this.value = false;
1373     },
1374     picker: function() {
1375         return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1376     },
1377     on_picker_select: function(text, instance) {
1378         var date = this.picker('getDate');
1379         this.$input.val(date ? this.format_client(date) : '').change();
1380     },
1381     set_value: function(value) {
1382         this.value = value;
1383         this.$input.val(value ? this.format_client(value) : '');
1384     },
1385     get_value: function() {
1386         return this.value;
1387     },
1388     set_value_from_ui: function() {
1389         var value = this.$input.val() || false;
1390         this.value = this.parse_client(value);
1391     },
1392     set_readonly: function(readonly) {
1393         this.readonly = readonly;
1394         this.$input.prop('disabled', this.readonly);
1395         this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1396     },
1397     is_valid: function(required) {
1398         var value = this.$input.val();
1399         if (value === "") {
1400             return !required;
1401         } else {
1402             try {
1403                 this.parse_client(value);
1404                 return true;
1405             } catch(e) {
1406                 return false;
1407             }
1408         }
1409     },
1410     focus: function() {
1411         this.$input.focus();
1412     },
1413     parse_client: function(v) {
1414         return openerp.web.parse_value(v, {"widget": this.type_of_date});
1415     },
1416     format_client: function(v) {
1417         return openerp.web.format_value(v, {"widget": this.type_of_date});
1418     },
1419     on_change: function() {
1420         if (this.is_valid()) {
1421             this.set_value_from_ui();
1422         }
1423     }
1424 });
1425
1426 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1427     jqueryui_object: 'datepicker',
1428     type_of_date: "date"
1429 });
1430
1431 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1432     template: "EmptyComponent",
1433     build_widget: function() {
1434         return new openerp.web.DateTimeWidget(this);
1435     },
1436     start: function() {
1437         var self = this;
1438         this._super.apply(this, arguments);
1439         this.datewidget = this.build_widget();
1440         this.datewidget.on_change.add_last(this.on_ui_change);
1441         this.datewidget.appendTo(this.$element);
1442     },
1443     set_value: function(value) {
1444         this._super(value);
1445         this.datewidget.set_value(value);
1446     },
1447     get_value: function() {
1448         return this.datewidget.get_value();
1449     },
1450     update_dom: function() {
1451         this._super.apply(this, arguments);
1452         this.datewidget.set_readonly(this.readonly);
1453     },
1454     validate: function() {
1455         this.invalid = !this.datewidget.is_valid(this.required);
1456     },
1457     focus: function() {
1458         this.datewidget.focus();
1459     }
1460 });
1461
1462 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1463     build_widget: function() {
1464         return new openerp.web.DateWidget(this);
1465     }
1466 });
1467
1468 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1469     template: 'FieldText',
1470     start: function() {
1471         this._super.apply(this, arguments);
1472         this.$element.find('textarea').change(this.on_ui_change);
1473     },
1474     set_value: function(value) {
1475         this._super.apply(this, arguments);
1476         var show_value = openerp.web.format_value(value, this, '');
1477         this.$element.find('textarea').val(show_value);
1478     },
1479     update_dom: function() {
1480         this._super.apply(this, arguments);
1481         this.$element.find('textarea').prop('disabled', this.readonly);
1482     },
1483     set_value_from_ui: function() {
1484         this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1485         this._super();
1486     },
1487     validate: function() {
1488         this.invalid = false;
1489         try {
1490             var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1491             this.invalid = this.required && value === '';
1492         } catch(e) {
1493             this.invalid = true;
1494         }
1495     },
1496     focus: function() {
1497         this.$element.find('textarea').focus();
1498     }
1499 });
1500
1501 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1502     template: 'FieldBoolean',
1503     start: function() {
1504         var self = this;
1505         this._super.apply(this, arguments);
1506         this.$element.find('input').click(self.on_ui_change);
1507     },
1508     set_value: function(value) {
1509         this._super.apply(this, arguments);
1510         this.$element.find('input')[0].checked = value;
1511     },
1512     set_value_from_ui: function() {
1513         this.value = this.$element.find('input').is(':checked');
1514         this._super();
1515     },
1516     update_dom: function() {
1517         this._super.apply(this, arguments);
1518         this.$element.find('input').prop('disabled', this.readonly);
1519     },
1520     focus: function() {
1521         this.$element.find('input').focus();
1522     }
1523 });
1524
1525 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1526     template: 'FieldProgressBar',
1527     start: function() {
1528         this._super.apply(this, arguments);
1529         this.$element.find('div').progressbar({
1530             value: this.value,
1531             disabled: this.readonly
1532         });
1533     },
1534     set_value: function(value) {
1535         this._super.apply(this, arguments);
1536         var show_value = Number(value);
1537         if (isNaN(show_value)) {
1538             show_value = 0;
1539         }
1540         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1541     }
1542 });
1543
1544 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1545 // to replace view editor
1546 });
1547
1548 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1549     template: 'FieldSelection',
1550     init: function(view, node) {
1551         var self = this;
1552         this._super(view, node);
1553         this.values = _.clone(this.field.selection);
1554         _.each(this.values, function(v, i) {
1555             if (v[0] === false && v[1] === '') {
1556                 self.values.splice(i, 1);
1557             }
1558         });
1559         this.values.unshift([false, '']);
1560     },
1561     start: function() {
1562         // Flag indicating whether we're in an event chain containing a change
1563         // event on the select, in order to know what to do on keyup[RETURN]:
1564         // * If the user presses [RETURN] as part of changing the value of a
1565         //   selection, we should just let the value change and not let the
1566         //   event broadcast further (e.g. to validating the current state of
1567         //   the form in editable list view, which would lead to saving the
1568         //   current row or switching to the next one)
1569         // * If the user presses [RETURN] with a select closed (side-effect:
1570         //   also if the user opened the select and pressed [RETURN] without
1571         //   changing the selected value), takes the action as validating the
1572         //   row
1573         var ischanging = false;
1574         this._super.apply(this, arguments);
1575         this.$element.find('select')
1576             .change(this.on_ui_change)
1577             .change(function () { ischanging = true; })
1578             .click(function () { ischanging = false; })
1579             .keyup(function (e) {
1580                 if (e.which !== 13 || !ischanging) { return; }
1581                 e.stopPropagation();
1582                 ischanging = false;
1583             });
1584     },
1585     set_value: function(value) {
1586         value = value === null ? false : value;
1587         value = value instanceof Array ? value[0] : value;
1588         this._super(value);
1589         var index = 0;
1590         for (var i = 0, ii = this.values.length; i < ii; i++) {
1591             if (this.values[i][0] === value) index = i;
1592         }
1593         this.$element.find('select')[0].selectedIndex = index;
1594     },
1595     set_value_from_ui: function() {
1596         this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1597         this._super();
1598     },
1599     update_dom: function() {
1600         this._super.apply(this, arguments);
1601         this.$element.find('select').prop('disabled', this.readonly);
1602     },
1603     validate: function() {
1604         var value = this.values[this.$element.find('select')[0].selectedIndex];
1605         this.invalid = !(value && !(this.required && value[0] === false));
1606     },
1607     focus: function() {
1608         this.$element.find('select').focus();
1609     }
1610 });
1611
1612 // jquery autocomplete tweak to allow html
1613 (function() {
1614     var proto = $.ui.autocomplete.prototype,
1615         initSource = proto._initSource;
1616
1617     function filter( array, term ) {
1618         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1619         return $.grep( array, function(value) {
1620             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1621         });
1622     }
1623
1624     $.extend( proto, {
1625         _initSource: function() {
1626             if ( this.options.html && $.isArray(this.options.source) ) {
1627                 this.source = function( request, response ) {
1628                     response( filter( this.options.source, request.term ) );
1629                 };
1630             } else {
1631                 initSource.call( this );
1632             }
1633         },
1634
1635         _renderItem: function( ul, item) {
1636             return $( "<li></li>" )
1637                 .data( "item.autocomplete", item )
1638                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1639                 .appendTo( ul );
1640         }
1641     });
1642 })();
1643
1644 openerp.web.form.dialog = function(content, options) {
1645     options = _.extend({
1646         autoOpen: true,
1647         width: '90%',
1648         height: '90%',
1649         min_width: '800px',
1650         min_height: '600px'
1651     }, options || {});
1652     options.autoOpen = true;
1653     var dialog = new openerp.web.Dialog(null, options);
1654     dialog.$dialog = $(content).dialog(dialog.dialog_options);
1655     return dialog.$dialog;
1656 };
1657
1658 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1659     template: 'FieldMany2One',
1660     init: function(view, node) {
1661         this._super(view, node);
1662         this.limit = 7;
1663         this.value = null;
1664         this.cm_id = _.uniqueId('m2o_cm_');
1665         this.last_search = [];
1666         this.tmp_value = undefined;
1667     },
1668     start: function() {
1669         this._super();
1670         var self = this;
1671         this.$input = this.$element.find("input");
1672         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1673         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1674
1675         // context menu
1676         var init_context_menu_def = $.Deferred().then(function(e) {
1677             var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1678             rdataset.call("get", ['action', 'client_action_relate',
1679                 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1680                 .then(function(result) {
1681                 self.related_entries = result;
1682
1683                 var $cmenu = $("#" + self.cm_id);
1684                 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1685                 var bindings = {};
1686                 bindings[self.cm_id + "_search"] = function() {
1687                     self._search_create_popup("search");
1688                 };
1689                 bindings[self.cm_id + "_create"] = function() {
1690                     self._search_create_popup("form");
1691                 };
1692                 bindings[self.cm_id + "_open"] = function() {
1693                     if (!self.value) {
1694                         return;
1695                     }
1696                     var pop = new openerp.web.form.FormOpenPopup(self.view);
1697                     pop.show_element(self.field.relation, self.value[0],self.build_context(), {});
1698                     pop.on_write_completed.add_last(function() {
1699                         self.set_value(self.value[0]);
1700                     });
1701                 };
1702                 _.each(_.range(self.related_entries.length), function(i) {
1703                     bindings[self.cm_id + "_related_" + i] = function() {
1704                         self.open_related(self.related_entries[i]);
1705                     };
1706                 });
1707                 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'leftClickToo': true,
1708                     bindings: bindings, itemStyle: {"color": ""},
1709                     onContextMenu: function() {
1710                         if(self.value) {
1711                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1712                         } else {
1713                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1714                         }
1715                         if (!self.readonly) {
1716                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1717                         } else {
1718                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1719                         }
1720                         return true;
1721                     }, menuStyle: {width: "200px"}
1722                 });
1723                 setTimeout(function() {self.$menu_btn.trigger(e);}, 0);
1724             });
1725         });
1726         var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1727         this.$menu_btn.bind('contextmenu', ctx_callback);
1728         this.$menu_btn.click(ctx_callback);
1729
1730         // some behavior for input
1731         this.$input.keyup(function() {
1732             if (self.$input.val() === "") {
1733                 self._change_int_value(null);
1734             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1735                 self._change_int_value(undefined);
1736             }
1737         });
1738         this.$drop_down.click(function() {
1739             if (self.readonly)
1740                 return;
1741             if (self.$input.autocomplete("widget").is(":visible")) {
1742                 self.$input.autocomplete("close");
1743             } else {
1744                 if (self.value) {
1745                     self.$input.autocomplete("search", "");
1746                 } else {
1747                     self.$input.autocomplete("search");
1748                 }
1749                 self.$input.focus();
1750             }
1751         });
1752         var anyoneLoosesFocus = function() {
1753             if (!self.$input.is(":focus") &&
1754                     !self.$input.autocomplete("widget").is(":visible") &&
1755                     !self.value) {
1756                 if (self.value === undefined && self.last_search.length > 0) {
1757                     self._change_int_ext_value(self.last_search[0]);
1758                 } else {
1759                     self._change_int_ext_value(null);
1760                 }
1761             }
1762         };
1763         this.$input.focusout(anyoneLoosesFocus);
1764
1765         var isSelecting = false;
1766         // autocomplete
1767         this.$input.autocomplete({
1768             source: function(req, resp) { self.get_search_result(req, resp); },
1769             select: function(event, ui) {
1770                 isSelecting = true;
1771                 var item = ui.item;
1772                 if (item.id) {
1773                     self._change_int_value([item.id, item.name]);
1774                 } else if (item.action) {
1775                     self._change_int_value(undefined);
1776                     item.action();
1777                     return false;
1778                 }
1779             },
1780             focus: function(e, ui) {
1781                 e.preventDefault();
1782             },
1783             html: true,
1784             close: anyoneLoosesFocus,
1785             minLength: 0,
1786             delay: 0
1787         });
1788         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
1789         this.$input.keyup(function(e) {
1790             if (e.which === 13) {
1791                 if (isSelecting)
1792                     e.stopPropagation();
1793             }
1794             isSelecting = false;
1795         });
1796     },
1797     // autocomplete component content handling
1798     get_search_result: function(request, response) {
1799         var search_val = request.term;
1800         var self = this;
1801
1802         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1803
1804         dataset.name_search(search_val, self.build_domain(), 'ilike',
1805                 this.limit + 1, function(data) {
1806             self.last_search = data;
1807             // possible selections for the m2o
1808             var values = _.map(data, function(x) {
1809                 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1810             });
1811
1812             // search more... if more results that max
1813             if (values.length > self.limit) {
1814                 values = values.slice(0, self.limit);
1815                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
1816                     dataset.name_search(search_val, self.build_domain(), 'ilike'
1817                     , false, function(data) {
1818                         self._change_int_value(null);
1819                         self._search_create_popup("search", data);
1820                     });
1821                 }});
1822             }
1823             // quick create
1824             var raw_result = _(data.result).map(function(x) {return x[1];});
1825             if (search_val.length > 0 &&
1826                 !_.include(raw_result, search_val) &&
1827                 (!self.value || search_val !== self.value[1])) {
1828                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
1829                         $('<span />').text(search_val).html()), action: function() {
1830                     self._quick_create(search_val);
1831                 }});
1832             }
1833             // create...
1834             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
1835                 self._change_int_value(null);
1836                 self._search_create_popup("form", undefined, {"default_name": search_val});
1837             }});
1838
1839             response(values);
1840         });
1841     },
1842     _quick_create: function(name) {
1843         var self = this;
1844         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1845         dataset.name_create(name, function(data) {
1846             self._change_int_ext_value(data);
1847         }).fail(function(error, event) {
1848             event.preventDefault();
1849             self._change_int_value(null);
1850             self._search_create_popup("form", undefined, {"default_name": name});
1851         });
1852     },
1853     // all search/create popup handling
1854     _search_create_popup: function(view, ids, context) {
1855         var self = this;
1856         var pop = new openerp.web.form.SelectCreatePopup(this);
1857         pop.select_element(self.field.relation,{
1858                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1859                 initial_view: view,
1860                 disable_multiple_selection: true
1861                 }, self.build_domain(),
1862                 new openerp.web.CompoundContext(self.build_context(), context || {}));
1863         pop.on_select_elements.add(function(element_ids) {
1864             var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
1865             dataset.name_get([element_ids[0]], function(data) {
1866                 self._change_int_ext_value(data[0]);
1867             });
1868         });
1869     },
1870     _change_int_ext_value: function(value) {
1871         this._change_int_value(value);
1872         this.$input.val(this.value ? this.value[1] : "");
1873     },
1874     _change_int_value: function(value) {
1875         this.value = value;
1876         var back_orig_value = this.original_value;
1877         if (this.value === null || this.value) {
1878             this.original_value = this.value;
1879         }
1880         if (back_orig_value === undefined) { // first use after a set_value()
1881             return;
1882         }
1883         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1884                 !== (this.value ? this.value[0] : null))) {
1885             this.on_ui_change();
1886         }
1887     },
1888     set_value: function(value) {
1889         value = value || null;
1890         this.invalid = false;
1891         var self = this;
1892         this.tmp_value = value;
1893         self.update_dom();
1894         self.on_value_changed();
1895         var real_set_value = function(rval) {
1896             self.tmp_value = undefined;
1897             self.value = rval;
1898             self.original_value = undefined;
1899             self._change_int_ext_value(rval);
1900         };
1901         if (value && !(value instanceof Array)) {
1902             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
1903             dataset.name_get([value], function(data) {
1904                 real_set_value(data[0]);
1905             }).fail(function() {self.tmp_value = undefined;});
1906         } else {
1907             setTimeout(function() {real_set_value(value);}, 0);
1908         }
1909     },
1910     get_value: function() {
1911         if (this.tmp_value !== undefined) {
1912             if (this.tmp_value instanceof Array) {
1913                 return this.tmp_value[0];
1914             }
1915             return this.tmp_value ? this.tmp_value : false;
1916         }
1917         if (this.value === undefined)
1918             return this.original_value ? this.original_value[0] : false;
1919         return this.value ? this.value[0] : false;
1920     },
1921     validate: function() {
1922         this.invalid = false;
1923         var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
1924         if (val === null) {
1925             this.invalid = this.required;
1926         }
1927     },
1928     open_related: function(related) {
1929         var self = this;
1930         if (!self.value)
1931             return;
1932         var additional_context = {
1933                 active_id: self.value[0],
1934                 active_ids: [self.value[0]],
1935                 active_model: self.field.relation
1936         };
1937         self.rpc("/web/action/load", {
1938             action_id: related[2].id,
1939             context: additional_context
1940         }, function(result) {
1941             result.result.context = _.extend(result.result.context || {}, additional_context);
1942             self.do_action(result.result);
1943         });
1944     },
1945     focus: function () {
1946         this.$input.focus();
1947     },
1948     update_dom: function() {
1949         this._super.apply(this, arguments);
1950         this.$input.prop('disabled', this.readonly);
1951     }
1952 });
1953
1954 /*
1955 # Values: (0, 0,  { fields })    create
1956 #         (1, ID, { fields })    update
1957 #         (2, ID)                remove (delete)
1958 #         (3, ID)                unlink one (target id or target of relation)
1959 #         (4, ID)                link
1960 #         (5)                    unlink all (only valid for one2many)
1961 */
1962 var commands = {
1963     // (0, _, {values})
1964     CREATE: 0,
1965     'create': function (values) {
1966         return [commands.CREATE, false, values];
1967     },
1968     // (1, id, {values})
1969     UPDATE: 1,
1970     'update': function (id, values) {
1971         return [commands.UPDATE, id, values];
1972     },
1973     // (2, id[, _])
1974     DELETE: 2,
1975     'delete': function (id) {
1976         return [commands.DELETE, id, false];
1977     },
1978     // (3, id[, _]) removes relation, but not linked record itself
1979     FORGET: 3,
1980     'forget': function (id) {
1981         return [commands.FORGET, id, false];
1982     },
1983     // (4, id[, _])
1984     LINK_TO: 4,
1985     'link_to': function (id) {
1986         return [commands.LINK_TO, id, false];
1987     },
1988     // (5[, _[, _]])
1989     DELETE_ALL: 5,
1990     'delete_all': function () {
1991         return [5, false, false];
1992     },
1993     // (6, _, ids) replaces all linked records with provided ids
1994     REPLACE_WITH: 6,
1995     'replace_with': function (ids) {
1996         return [6, false, ids];
1997     }
1998 };
1999 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2000     template: 'FieldOne2Many',
2001     multi_selection: false,
2002     init: function(view, node) {
2003         this._super(view, node);
2004         this.is_loaded = $.Deferred();
2005         this.initial_is_loaded = this.is_loaded;
2006         this.is_setted = $.Deferred();
2007         this.form_last_update = $.Deferred();
2008         this.init_form_last_update = this.form_last_update;
2009         this.disable_utility_classes = true;
2010     },
2011     start: function() {
2012         this._super.apply(this, arguments);
2013
2014         var self = this;
2015
2016         this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2017         this.dataset.o2m = this;
2018         this.dataset.parent_view = this.view;
2019         this.dataset.on_change.add_last(function() {
2020             self.on_ui_change();
2021         });
2022
2023         this.is_setted.then(function() {
2024             self.load_views();
2025         });
2026     },
2027     is_readonly: function() {
2028         return this.readonly || this.force_readonly;
2029     },
2030     load_views: function() {
2031         var self = this;
2032         
2033         var modes = this.node.attrs.mode;
2034         modes = !!modes ? modes.split(",") : ["tree"];
2035         var views = [];
2036         _.each(modes, function(mode) {
2037             var view = {
2038                 view_id: false,
2039                 view_type: mode == "tree" ? "list" : mode,
2040                 options: { sidebar : false }
2041             };
2042             if (self.field.views && self.field.views[mode]) {
2043                 view.embedded_view = self.field.views[mode];
2044             }
2045             if(view.view_type === "list") {
2046                 view.options.selectable = self.multi_selection;
2047                 if (self.is_readonly()) {
2048                     view.options.addable = null;
2049                     view.options.deletable = null;
2050                 }
2051             } else if (view.view_type === "form") {
2052                 if (self.is_readonly()) {
2053                     view.view_type = 'page';
2054                 }
2055                 view.options.not_interactible_on_create = true;
2056             }
2057             views.push(view);
2058         });
2059         this.views = views;
2060
2061         this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {
2062             action_buttons : false
2063         });
2064         this.viewmanager.template = 'One2Many.viewmanager';
2065         this.viewmanager.registry = openerp.web.views.clone({
2066             list: 'openerp.web.form.One2ManyListView',
2067             form: 'openerp.web.FormView',
2068             page: 'openerp.web.PageView'
2069         });
2070         var once = $.Deferred().then(function() {
2071             self.init_form_last_update.resolve();
2072         });
2073         var def = $.Deferred().then(function() {
2074             self.initial_is_loaded.resolve();
2075         });
2076         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2077             if (view_type == "list") {
2078                 controller.o2m = self;
2079                 if (self.is_readonly())
2080                     controller.set_editable(false);
2081             } else if (view_type == "form" || view_type == 'page') {
2082                 if (view_type == 'page') {
2083                     controller.$element.find(".oe_form_buttons").hide();
2084                 }
2085                 controller.on_record_loaded.add_last(function() {
2086                     once.resolve();
2087                 });
2088                 controller.on_pager_action.add_first(function() {
2089                     self.save_any_view();
2090                 });
2091             } else if (view_type == "graph") {
2092                 self.reload_current_view()
2093             }
2094             def.resolve();
2095         });
2096         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2097             $.when(self.save_any_view()).then(function() {
2098                 if(n_mode === "list")
2099                     setTimeout(function() {self.reload_current_view();}, 0);
2100             });
2101         });
2102         this.is_setted.then(function() {
2103             setTimeout(function () {
2104                 self.viewmanager.appendTo(self.$element);
2105             }, 0);
2106         });
2107         return def;
2108     },
2109     reload_current_view: function() {
2110         var self = this;
2111         return self.is_loaded = self.is_loaded.pipe(function() {
2112             var active_view = self.viewmanager.active_view;
2113             var view = self.viewmanager.views[active_view].controller;
2114             if(active_view === "list") {
2115                 return view.reload_content();
2116             } else if (active_view === "form" || active_view === 'page') {
2117                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2118                     self.dataset.index = 0;
2119                 }
2120                 var act = function() {
2121                     return view.do_show();
2122                 };
2123                 self.form_last_update = self.form_last_update.pipe(act, act);
2124                 return self.form_last_update;
2125             } else if (active_view === "graph") {
2126                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2127             }
2128         }, undefined);
2129     },
2130     set_value: function(value) {
2131         value = value || [];
2132         var self = this;
2133         this.dataset.reset_ids([]);
2134         if(value.length >= 1 && value[0] instanceof Array) {
2135             var ids = [];
2136             _.each(value, function(command) {
2137                 var obj = {values: command[2]};
2138                 switch (command[0]) {
2139                     case commands.CREATE:
2140                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2141                         obj.defaults = {};
2142                         self.dataset.to_create.push(obj);
2143                         self.dataset.cache.push(_.clone(obj));
2144                         ids.push(obj.id);
2145                         return;
2146                     case commands.UPDATE:
2147                         obj['id'] = command[1];
2148                         self.dataset.to_write.push(obj);
2149                         self.dataset.cache.push(_.clone(obj));
2150                         ids.push(obj.id);
2151                         return;
2152                     case commands.DELETE:
2153                         self.dataset.to_delete.push({id: command[1]});
2154                         return;
2155                     case commands.LINK_TO:
2156                         ids.push(command[1]);
2157                         return;
2158                     case commands.DELETE_ALL:
2159                         self.dataset.delete_all = true;
2160                         return;
2161                 }
2162             });
2163             this._super(ids);
2164             this.dataset.set_ids(ids);
2165         } else if (value.length >= 1 && typeof(value[0]) === "object") {
2166             var ids = [];
2167             this.dataset.delete_all = true;
2168             _.each(value, function(command) {
2169                 var obj = {values: command};
2170                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2171                 obj.defaults = {};
2172                 self.dataset.to_create.push(obj);
2173                 self.dataset.cache.push(_.clone(obj));
2174                 ids.push(obj.id);
2175             });
2176             this._super(ids);
2177             this.dataset.set_ids(ids);
2178         } else {
2179             this._super(value);
2180             this.dataset.reset_ids(value);
2181         }
2182         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2183             this.dataset.index = 0;
2184         }
2185         self.is_setted.resolve();
2186         return self.reload_current_view();
2187     },
2188     get_value: function() {
2189         var self = this;
2190         if (!this.dataset)
2191             return [];
2192         this.save_any_view();
2193         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2194         val = val.concat(_.map(this.dataset.ids, function(id) {
2195             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2196             if (alter_order) {
2197                 return commands.create(alter_order.values);
2198             }
2199             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2200             if (alter_order) {
2201                 return commands.update(alter_order.id, alter_order.values);
2202             }
2203             return commands.link_to(id);
2204         }));
2205         return val.concat(_.map(
2206             this.dataset.to_delete, function(x) {
2207                 return commands['delete'](x.id);}));
2208     },
2209     save_any_view: function() {
2210         if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2211             this.viewmanager.views[this.viewmanager.active_view] &&
2212             this.viewmanager.views[this.viewmanager.active_view].controller) {
2213             var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2214             if (this.viewmanager.active_view === "form") {
2215                 var res = $.when(view.do_save());
2216                 // it seems line there are some cases when this happens
2217                 /*if (!res.isResolved() && !res.isRejected()) {
2218                     console.warn("Asynchronous get_value() is not supported in form view.");
2219                 }*/
2220                 return res;
2221             } else if (this.viewmanager.active_view === "list") {
2222                 var res = $.when(view.ensure_saved());
2223                 // it seems line there are some cases when this happens
2224                 /*if (!res.isResolved() && !res.isRejected()) {
2225                     console.warn("Asynchronous get_value() is not supported in list view.");
2226                 }*/
2227                 return res;
2228             }
2229         }
2230         return false;
2231     },
2232     is_valid: function() {
2233         this.validate();
2234         return this._super();
2235     },
2236     validate: function() {
2237         this.invalid = false;
2238         if (!this.viewmanager.views[this.viewmanager.active_view])
2239             return;
2240         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2241         if (this.viewmanager.active_view === "form") {
2242             for (var f in view.fields) {
2243                 f = view.fields[f];
2244                 if (!f.is_valid()) {
2245                     this.invalid = true;
2246                     return;
2247                 }
2248             }
2249         }
2250     },
2251     is_dirty: function() {
2252         this.save_any_view();
2253         return this._super();
2254     },
2255     update_dom: function() {
2256         this._super.apply(this, arguments);
2257         var self = this;
2258         if (this.previous_readonly !== this.readonly) {
2259             this.previous_readonly = this.readonly;
2260             if (this.viewmanager) {
2261                 this.is_loaded = this.is_loaded.pipe(function() {
2262                     self.viewmanager.stop();
2263                     return $.when(self.load_views()).then(function() {
2264                         self.reload_current_view();
2265                     });
2266                 });
2267             }
2268         }
2269     }
2270 });
2271
2272 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2273     get_context: function() {
2274         this.context = this.o2m.build_context();
2275         return this.context;
2276     }
2277 });
2278
2279 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2280     _template: 'One2Many.listview',
2281     do_add_record: function () {
2282         if (this.options.editable) {
2283             this._super.apply(this, arguments);
2284         } else {
2285             var self = this;
2286             var pop = new openerp.web.form.SelectCreatePopup(this);
2287             pop.on_default_get.add(self.dataset.on_default_get);
2288             pop.select_element(self.o2m.field.relation,{
2289                 initial_view: "form",
2290                 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2291                 create_function: function(data, callback, error_callback) {
2292                     return self.o2m.dataset.create(data).then(function(r) {
2293                         self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2294                         self.o2m.dataset.on_change();
2295                     }).then(callback, error_callback);
2296                 },
2297                 read_function: function() {
2298                     return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2299                 },
2300                 parent_view: self.o2m.view,
2301                 form_view_options: {'not_interactible_on_create':true}
2302             }, self.o2m.build_domain(), self.o2m.build_context());
2303             pop.on_select_elements.add_last(function() {
2304                 self.o2m.reload_current_view();
2305             });
2306         }
2307     },
2308     do_activate_record: function(index, id) {
2309         var self = this;
2310         var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2311         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(),{
2312             auto_write: false,
2313             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2314             parent_view: self.o2m.view,
2315             read_function: function() {
2316                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2317             },
2318             form_view_options: {'not_interactible_on_create':true},
2319             readonly: self.o2m.is_readonly()
2320         });
2321         pop.on_write.add(function(id, data) {
2322             self.o2m.dataset.write(id, data, {}, function(r) {
2323                 self.o2m.reload_current_view();
2324             });
2325         });
2326     }
2327 });
2328
2329 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2330     template: 'FieldMany2Many',
2331     multi_selection: false,
2332     init: function(view, node) {
2333         this._super(view, node);
2334         this.list_id = _.uniqueId("many2many");
2335         this.is_loaded = $.Deferred();
2336         this.initial_is_loaded = this.is_loaded;
2337         this.is_setted = $.Deferred();
2338     },
2339     start: function() {
2340         this._super.apply(this, arguments);
2341
2342         var self = this;
2343
2344         this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2345         this.dataset.m2m = this;
2346         this.dataset.on_unlink.add_last(function(ids) {
2347             self.on_ui_change();
2348         });
2349         
2350         this.is_setted.then(function() {
2351             self.load_view();
2352         });
2353     },
2354     set_value: function(value) {
2355         value = value || [];
2356         if (value.length >= 1 && value[0] instanceof Array) {
2357             value = value[0][2];
2358         }
2359         this._super(value);
2360         this.dataset.set_ids(value);
2361         var self = this;
2362         self.reload_content();
2363         this.is_setted.resolve();
2364     },
2365     get_value: function() {
2366         return [commands.replace_with(this.dataset.ids)];
2367     },
2368     validate: function() {
2369         this.invalid = false;
2370     },
2371     is_readonly: function() {
2372         return this.readonly || this.force_readonly;
2373     },
2374     load_view: function() {
2375         var self = this;
2376         this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2377                     'addable': self.is_readonly() ? null : _t("Add"),
2378                     'deletable': self.is_readonly() ? false : true,
2379                     'selectable': self.multi_selection
2380             });
2381         var embedded = (this.field.views || {}).tree;
2382         if (embedded) {
2383             this.list_view.set_embedded_view(embedded);
2384         }
2385         this.list_view.m2m_field = this;
2386         var loaded = $.Deferred();
2387         this.list_view.on_loaded.add_last(function() {
2388             self.initial_is_loaded.resolve();
2389             loaded.resolve();
2390         });
2391         setTimeout(function () {
2392             self.list_view.appendTo($("#" + self.list_id));
2393         }, 0);
2394         return loaded;
2395     },
2396     reload_content: function() {
2397         var self = this;
2398         this.is_loaded = this.is_loaded.pipe(function() {
2399             return self.list_view.reload_content();
2400         });
2401     },
2402     update_dom: function() {
2403         this._super.apply(this, arguments);
2404         var self = this;
2405         if (this.previous_readonly !== this.readonly) {
2406             this.previous_readonly = this.readonly;
2407             if (this.list_view) {
2408                 this.is_loaded = this.is_loaded.pipe(function() {
2409                     self.list_view.stop();
2410                     return $.when(self.load_view()).then(function() {
2411                         self.reload_content();
2412                     });
2413                 });
2414             }
2415         }
2416     }
2417 });
2418
2419 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2420     get_context: function() {
2421         this.context = this.m2m.build_context();
2422         return this.context;
2423     }
2424 });
2425
2426 /**
2427  * @class
2428  * @extends openerp.web.ListView
2429  */
2430 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2431     do_add_record: function () {
2432         var pop = new openerp.web.form.SelectCreatePopup(this);
2433         pop.select_element(this.model, {},
2434             new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2435             this.m2m_field.build_context());
2436         var self = this;
2437         pop.on_select_elements.add(function(element_ids) {
2438             _.each(element_ids, function(element_id) {
2439                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2440                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2441                     self.m2m_field.on_ui_change();
2442                     self.reload_content();
2443                 }
2444             });
2445         });
2446     },
2447     do_activate_record: function(index, id) {
2448         var self = this;
2449         var pop = new openerp.web.form.FormOpenPopup(this);
2450         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2451             readonly: this.widget_parent.is_readonly()
2452         });
2453         pop.on_write_completed.add_last(function() {
2454             self.reload_content();
2455         });
2456     }
2457 });
2458
2459 /**
2460  * @class
2461  * @extends openerp.web.OldWidget
2462  */
2463 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2464     identifier_prefix: "selectcreatepopup",
2465     template: "SelectCreatePopup",
2466     /**
2467      * options:
2468      * - initial_ids
2469      * - initial_view: form or search (default search)
2470      * - disable_multiple_selection
2471      * - alternative_form_view
2472      * - create_function (defaults to a naive saving behavior)
2473      * - parent_view
2474      * - form_view_options
2475      * - list_view_options
2476      * - read_function
2477      */
2478     select_element: function(model, options, domain, context) {
2479         var self = this;
2480         this.model = model;
2481         this.domain = domain || [];
2482         this.context = context || {};
2483         this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2484             return self.create_row.apply(self, arguments);
2485         }, read_function: null});
2486         this.initial_ids = this.options.initial_ids;
2487         this.created_elements = [];
2488         this.render_element();
2489         openerp.web.form.dialog(this.$element, {close:function() {
2490             self.check_exit();
2491         }});
2492         this.start();
2493     },
2494     start: function() {
2495         this._super();
2496         var self = this;
2497         this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2498             this.context);
2499         this.dataset.create_function = function() {
2500             return self.options.create_function.apply(null, arguments).then(function(r) {
2501                 self.created_elements.push(r.result);
2502             });
2503         };
2504         this.dataset.write_function = function() {
2505             return self.write_row.apply(self, arguments);
2506         };
2507         this.dataset.read_function = this.options.read_function;
2508         this.dataset.parent_view = this.options.parent_view;
2509         this.dataset.on_default_get.add(this.on_default_get);
2510         if (this.options.initial_view == "search") {
2511             self.rpc('/web/session/eval_domain_and_context', {
2512                 domains: [],
2513                 contexts: [this.context]
2514             }, function (results) {
2515                 var search_defaults = {};
2516                 _.each(results.context, function (value, key) {
2517                     var match = /^search_default_(.*)$/.exec(key);
2518                     if (match) {
2519                         search_defaults[match[1]] = value;
2520                     }
2521                 });
2522                 self.setup_search_view(search_defaults);
2523             });
2524         } else { // "form"
2525             this.new_object();
2526         }
2527     },
2528     setup_search_view: function(search_defaults) {
2529         var self = this;
2530         if (this.searchview) {
2531             this.searchview.stop();
2532         }
2533         this.searchview = new openerp.web.SearchView(this,
2534                 this.dataset, false,  search_defaults);
2535         this.searchview.on_search.add(function(domains, contexts, groupbys) {
2536             if (self.initial_ids) {
2537                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2538                     contexts, groupbys);
2539                 self.initial_ids = undefined;
2540             } else {
2541                 self.do_search(domains.concat([self.domain]), contexts, groupbys);
2542             }
2543         });
2544         this.searchview.on_loaded.add_last(function () {
2545             var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
2546             $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
2547             var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2548             $cbutton.click(function() {
2549                 self.stop();
2550             });
2551             var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2552             if(self.options.disable_multiple_selection) {
2553                 $sbutton.hide();
2554             }
2555             $sbutton.click(function() {
2556                 self.on_select_elements(self.selected_ids);
2557                 self.stop();
2558             });
2559             self.view_list = new openerp.web.form.SelectCreateListView(self,
2560                     self.dataset, false,
2561                     _.extend({'deletable': false,
2562                         'selectable': !self.options.disable_multiple_selection
2563                     }, self.options.list_view_options || {}));
2564             self.view_list.popup = self;
2565             self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2566                 self.view_list.do_show();
2567             }).pipe(function() {
2568                 self.searchview.do_search();
2569             });
2570         });
2571         this.searchview.appendTo($("#" + this.element_id + "_search"));
2572     },
2573     do_search: function(domains, contexts, groupbys) {
2574         var self = this;
2575         this.rpc('/web/session/eval_domain_and_context', {
2576             domains: domains || [],
2577             contexts: contexts || [],
2578             group_by_seq: groupbys || []
2579         }, function (results) {
2580             self.view_list.do_search(results.domain, results.context, results.group_by);
2581         });
2582     },
2583     create_row: function() {
2584         var self = this;
2585         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2586         wdataset.parent_view = this.options.parent_view;
2587         return wdataset.create.apply(wdataset, arguments);
2588     },
2589     write_row: function() {
2590         var self = this;
2591         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2592         wdataset.parent_view = this.options.parent_view;
2593         return wdataset.write.apply(wdataset, arguments);
2594     },
2595     on_select_elements: function(element_ids) {
2596     },
2597     on_click_element: function(ids) {
2598         this.selected_ids = ids || [];
2599         if(this.selected_ids.length > 0) {
2600             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2601         } else {
2602             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2603         }
2604     },
2605     new_object: function() {
2606         var self = this;
2607         if (this.searchview) {
2608             this.searchview.hide();
2609         }
2610         if (this.view_list) {
2611             this.view_list.$element.hide();
2612         }
2613         this.dataset.index = null;
2614         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2615         if (this.options.alternative_form_view) {
2616             this.view_form.set_embedded_view(this.options.alternative_form_view);
2617         }
2618         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2619         this.view_form.on_loaded.add_last(function() {
2620             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2621             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2622             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2623             $nbutton.click(function() {
2624                 $.when(self.view_form.do_save()).then(function() {
2625                     self.view_form.reload_lock.then(function() {
2626                         self.view_form.on_button_new();
2627                     });
2628                 });
2629             });
2630             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2631             $nbutton.click(function() {
2632                 $.when(self.view_form.do_save()).then(function() {
2633                     self.view_form.reload_lock.then(function() {
2634                         self.check_exit();
2635                     });
2636                 });
2637             });
2638             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2639             $cbutton.click(function() {
2640                 self.check_exit();
2641             });
2642         });
2643         this.view_form.do_show();
2644     },
2645     check_exit: function() {
2646         if (this.created_elements.length > 0) {
2647             this.on_select_elements(this.created_elements);
2648         }
2649         this.stop();
2650     },
2651     on_default_get: function(res) {}
2652 });
2653
2654 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2655     do_add_record: function () {
2656         this.popup.new_object();
2657     },
2658     select_record: function(index) {
2659         this.popup.on_select_elements([this.dataset.ids[index]]);
2660         this.popup.stop();
2661     },
2662     do_select: function(ids, records) {
2663         this._super(ids, records);
2664         this.popup.on_click_element(ids);
2665     }
2666 });
2667
2668 /**
2669  * @class
2670  * @extends openerp.web.OldWidget
2671  */
2672 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2673     identifier_prefix: "formopenpopup",
2674     template: "FormOpenPopup",
2675     /**
2676      * options:
2677      * - alternative_form_view
2678      * - auto_write (default true)
2679      * - read_function
2680      * - parent_view
2681      * - form_view_options
2682      * - readonly
2683      */
2684     show_element: function(model, row_id, context, options) {
2685         this.model = model;
2686         this.row_id = row_id;
2687         this.context = context || {};
2688         this.options = _.defaults(options || {}, {"auto_write": true});
2689         this.render_element();
2690         this.$element.dialog({title: '',
2691                     modal: true,
2692                     width: 960,
2693                     height: 600});
2694         this.start();
2695     },
2696     start: function() {
2697         this._super();
2698         this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
2699         this.dataset.fop = this;
2700         this.dataset.ids = [this.row_id];
2701         this.dataset.index = 0;
2702         this.dataset.parent_view = this.options.parent_view;
2703         this.setup_form_view();
2704     },
2705     on_write: function(id, data) {
2706         if (!this.options.auto_write)
2707             return;
2708         var self = this;
2709         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2710         wdataset.parent_view = this.options.parent_view;
2711         wdataset.write(id, data, {}, function(r) {
2712             self.on_write_completed();
2713         });
2714     },
2715     on_write_completed: function() {},
2716     setup_form_view: function() {
2717         var self = this;
2718         var FormClass = this.options.readonly
2719                 ? openerp.web.views.get_object('page')
2720                 : openerp.web.views.get_object('form');
2721         this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
2722         if (this.options.alternative_form_view) {
2723             this.view_form.set_embedded_view(this.options.alternative_form_view);
2724         }
2725         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2726         this.view_form.on_loaded.add_last(function() {
2727             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2728             $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
2729             var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
2730             $nbutton.click(function() {
2731                 self.view_form.do_save().then(function() {
2732                     self.stop();
2733                 });
2734             });
2735             var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
2736             $cbutton.click(function() {
2737                 self.stop();
2738             });
2739             if (self.options.readonly) {
2740                 $nbutton.hide();
2741                 $cbutton.text(_t("Close"));
2742             }
2743             self.view_form.do_show();
2744         });
2745         this.dataset.on_write.add(this.on_write);
2746     }
2747 });
2748
2749 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
2750     read_ids: function() {
2751         if (this.fop.options.read_function) {
2752             return this.fop.options.read_function.apply(null, arguments);
2753         } else {
2754             return this._super.apply(this, arguments);
2755         }
2756     }
2757 });
2758
2759 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
2760     template: 'FieldReference',
2761     init: function(view, node) {
2762         this._super(view, node);
2763         this.fields_view = {
2764             fields: {
2765                 selection: {
2766                     selection: view.fields_view.fields[this.name].selection
2767                 },
2768                 m2o: {
2769                     relation: null
2770                 }
2771             }
2772         };
2773         this.get_fields_values = view.get_fields_values;
2774         this.do_onchange = this.on_form_changed = this.on_nop;
2775         this.dataset = this.view.dataset;
2776         this.widgets_counter = 0;
2777         this.view_id = 'reference_' + _.uniqueId();
2778         this.widgets = {};
2779         this.fields = {};
2780         this.fields_order = [];
2781         this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
2782             name: 'selection',
2783             widget: 'selection'
2784         }});
2785         this.reference_ready = true;
2786         this.selection.on_value_changed.add_last(this.on_selection_changed);
2787         this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
2788             name: 'm2o',
2789             widget: 'many2one'
2790         }});
2791     },
2792     on_nop: function() {
2793     },
2794     on_selection_changed: function() {
2795         if (this.reference_ready) {
2796             var sel = this.selection.get_value();
2797             this.m2o.field.relation = sel;
2798             this.m2o.set_value(null);
2799             this.m2o.$element.toggle(sel !== false);
2800         }
2801     },
2802     start: function() {
2803         this._super();
2804         this.selection.start();
2805         this.m2o.start();
2806     },
2807     is_valid: function() {
2808         return this.required === false || typeof(this.get_value()) === 'string';
2809     },
2810     is_dirty: function() {
2811         return this.selection.is_dirty() || this.m2o.is_dirty();
2812     },
2813     set_value: function(value) {
2814         this._super(value);
2815         this.reference_ready = false;
2816         var vals = [], sel_val, m2o_val;
2817         if (typeof(value) === 'string') {
2818             vals = value.split(',');
2819         }
2820         sel_val = vals[0] || false;
2821         m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
2822         this.selection.set_value(sel_val);
2823         this.m2o.field.relation = sel_val;
2824         this.m2o.set_value(m2o_val);
2825         this.m2o.$element.toggle(sel_val !== false);
2826         this.reference_ready = true;
2827     },
2828     get_value: function() {
2829         var model = this.selection.get_value(),
2830             id = this.m2o.get_value();
2831         if (typeof(model) === 'string' && typeof(id) === 'number') {
2832             return model + ',' + id;
2833         } else {
2834             return false;
2835         }
2836     }
2837 });
2838
2839 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
2840     init: function(view, node) {
2841         this._super(view, node);
2842         this.iframe = this.element_id + '_iframe';
2843         this.binary_value = false;
2844     },
2845     start: function() {
2846         this._super.apply(this, arguments);
2847         this.$element.find('input.oe-binary-file').change(this.on_file_change);
2848         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
2849         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
2850     },
2851     human_filesize : function(size) {
2852         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2853         var i = 0;
2854         while (size >= 1024) {
2855             size /= 1024;
2856             ++i;
2857         }
2858         return size.toFixed(2) + ' ' + units[i];
2859     },
2860     on_file_change: function(e) {
2861         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
2862         // http://www.html5rocks.com/tutorials/file/dndfiles/
2863         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
2864         window[this.iframe] = this.on_file_uploaded;
2865         if ($(e.target).val() != '') {
2866             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
2867             this.$element.find('form.oe-binary-form').submit();
2868             this.$element.find('.oe-binary-progress').show();
2869             this.$element.find('.oe-binary').hide();
2870         }
2871     },
2872     on_file_uploaded: function(size, name, content_type, file_base64) {
2873         delete(window[this.iframe]);
2874         if (size === false) {
2875             this.do_warn("File Upload", "There was a problem while uploading your file");
2876             // TODO: use openerp web crashmanager
2877             console.warn("Error while uploading file : ", name);
2878         } else {
2879             this.on_file_uploaded_and_valid.apply(this, arguments);
2880             this.on_ui_change();
2881         }
2882         this.$element.find('.oe-binary-progress').hide();
2883         this.$element.find('.oe-binary').show();
2884     },
2885     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2886     },
2887     on_save_as: function() {
2888         var url = '/web/binary/saveas?session_id=' + this.session.session_id + '&model=' +
2889             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
2890             '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime());
2891         window.open(url);
2892     },
2893     on_clear: function() {
2894         if (this.value !== false) {
2895             this.value = false;
2896             this.binary_value = false;
2897             this.on_ui_change();
2898         }
2899         return false;
2900     }
2901 });
2902
2903 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
2904     template: 'FieldBinaryFile',
2905     update_dom: function() {
2906         this._super.apply(this, arguments);
2907         this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
2908         this.$element.find('input[type=text]').prop('disabled', this.readonly);
2909     },
2910     set_value: function(value) {
2911         this._super.apply(this, arguments);
2912         var show_value = (value != null && value !== false) ? value : '';
2913         this.$element.find('input').eq(0).val(show_value);
2914     },
2915     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2916         this.value = file_base64;
2917         this.binary_value = true;
2918         var show_value = this.human_filesize(size);
2919         this.$element.find('input').eq(0).val(show_value);
2920         this.set_filename(name);
2921     },
2922     set_filename: function(value) {
2923         var filename = this.node.attrs.filename;
2924         if (this.view.fields[filename]) {
2925             this.view.fields[filename].set_value(value);
2926             this.view.fields[filename].on_ui_change();
2927         }
2928     },
2929     on_clear: function() {
2930         this._super.apply(this, arguments);
2931         this.$element.find('input').eq(0).val('');
2932         this.set_filename('');
2933     }
2934 });
2935
2936 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
2937     template: 'FieldBinaryImage',
2938     start: function() {
2939         this._super.apply(this, arguments);
2940         this.$image = this.$element.find('img.oe-binary-image');
2941     },
2942     update_dom: function() {
2943         this._super.apply(this, arguments);
2944         this.$element.find('.oe-binary').toggle(!this.readonly);
2945     },
2946     set_value: function(value) {
2947         this._super.apply(this, arguments);
2948         this.set_image_maxwidth();
2949         var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
2950             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
2951         this.$image.attr('src', url);
2952     },
2953     set_image_maxwidth: function() {
2954         this.$image.css('max-width', this.$element.width());
2955     },
2956     on_file_change: function() {
2957         this.set_image_maxwidth();
2958         this._super.apply(this, arguments);
2959     },
2960     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2961         this.value = file_base64;
2962         this.binary_value = true;
2963         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
2964     },
2965     on_clear: function() {
2966         this._super.apply(this, arguments);
2967         this.$image.attr('src', '/web/static/src/img/placeholder.png');
2968     }
2969 });
2970
2971 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
2972     template: "EmptyComponent",
2973     start: function() {
2974         this._super();
2975         this.selected_value = null;
2976
2977         this.render_list();
2978     },
2979     set_value: function(value) {
2980         this._super(value);
2981         this.selected_value = value;
2982
2983         this.render_list();
2984     },
2985     render_list: function() {
2986         var self = this;
2987         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
2988             function(x) { return _.str.trim(x); });
2989         shown = _.select(shown, function(x) { return x.length > 0; });
2990
2991         if (shown.length == 0) {
2992             this.to_show = this.field.selection;
2993         } else {
2994             this.to_show = _.select(this.field.selection, function(x) {
2995                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
2996             });
2997         }
2998
2999         var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3000         this.$element.html(content);
3001
3002         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3003         var color = colors[this.selected_value];
3004         if (color) {
3005             var elem = this.$element.find("li.oe-arrow-list-selected span");
3006             elem.css("border-color", color);
3007             if (this.check_white(color))
3008                 elem.css("color", "white");
3009             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3010             elem.css("border-left-color", "rgba(0,0,0,0)");
3011             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3012             elem.css("border-color", "rgba(0,0,0,0)");
3013             elem.css("border-left-color", color);
3014         }
3015     },
3016     check_white: function(color) {
3017         var div = $("<div></div>");
3018         div.css("display", "none");
3019         div.css("color", color);
3020         div.appendTo($("body"));
3021         var ncolor = div.css("color");
3022         div.remove();
3023         var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3024         if (!res) {
3025             return false;
3026         }
3027         var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3028         var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3029         if (lum < 128) {
3030             return true;
3031         }
3032         return false;
3033     }
3034 });
3035
3036
3037
3038 /**
3039  * Registry of form widgets, called by :js:`openerp.web.FormView`
3040  */
3041 openerp.web.form.widgets = new openerp.web.Registry({
3042     'frame' : 'openerp.web.form.WidgetFrame',
3043     'group' : 'openerp.web.form.WidgetGroup',
3044     'notebook' : 'openerp.web.form.WidgetNotebook',
3045     'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3046     'separator' : 'openerp.web.form.WidgetSeparator',
3047     'label' : 'openerp.web.form.WidgetLabel',
3048     'button' : 'openerp.web.form.WidgetButton',
3049     'char' : 'openerp.web.form.FieldChar',
3050     'email' : 'openerp.web.form.FieldEmail',
3051     'url' : 'openerp.web.form.FieldUrl',
3052     'text' : 'openerp.web.form.FieldText',
3053     'text_wiki' : 'openerp.web.form.FieldText',
3054     'date' : 'openerp.web.form.FieldDate',
3055     'datetime' : 'openerp.web.form.FieldDatetime',
3056     'selection' : 'openerp.web.form.FieldSelection',
3057     'many2one' : 'openerp.web.form.FieldMany2One',
3058     'many2many' : 'openerp.web.form.FieldMany2Many',
3059     'one2many' : 'openerp.web.form.FieldOne2Many',
3060     'one2many_list' : 'openerp.web.form.FieldOne2Many',
3061     'reference' : 'openerp.web.form.FieldReference',
3062     'boolean' : 'openerp.web.form.FieldBoolean',
3063     'float' : 'openerp.web.form.FieldFloat',
3064     'integer': 'openerp.web.form.FieldFloat',
3065     'float_time': 'openerp.web.form.FieldFloat',
3066     'progressbar': 'openerp.web.form.FieldProgressBar',
3067     'image': 'openerp.web.form.FieldBinaryImage',
3068     'binary': 'openerp.web.form.FieldBinaryFile',
3069     'statusbar': 'openerp.web.form.FieldStatus'
3070 });
3071
3072
3073 };
3074
3075 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: