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