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