[FIX] WidgetFrame fetches fields_view.fields property on non 'field' tags
[odoo/odoo.git] / addons / base / static / src / js / form.js
1 openerp.base.form = function (openerp) {
2
3 openerp.base.views.add('form', 'openerp.base.FormView');
4 openerp.base.FormView =  openerp.base.View.extend( /** @lends openerp.base.FormView# */{
5     /**
6      * Indicates that this view is not searchable, and thus that no search
7      * view should be displayed (if there is one active).
8      */
9     searchable: false,
10     template: "FormView",
11     /**
12      * @constructs
13      * @param {openerp.base.Session} session the current openerp session
14      * @param {String} element_id this view's root element id
15      * @param {openerp.base.DataSet} dataset the dataset this view will work with
16      * @param {String} view_id the identifier of the OpenERP view object
17      *
18      * @property {openerp.base.Registry} registry=openerp.base.form.widgets widgets registry for this form view instance
19      */
20     init: function(view_manager, session, element_id, dataset, view_id) {
21         this._super(session, element_id);
22         this.view_manager = view_manager || new openerp.base.NullViewManager();
23         this.dataset = dataset;
24         this.model = dataset.model;
25         this.view_id = view_id;
26         this.fields_view = {};
27         this.widgets = {};
28         this.widgets_counter = 0;
29         this.fields = {};
30         this.datarecord = {};
31         this.ready = false;
32         this.show_invalid = true;
33         this.touched = false;
34         this.flags = this.view_manager.flags || {};
35         this.default_focus_field = null;
36         this.default_focus_button = null;
37         this.registry = openerp.base.form.widgets;
38         this.has_been_loaded = $.Deferred();
39         this.$form_header = null;
40     },
41     start: function() {
42         //this.log('Starting FormView '+this.model+this.view_id)
43         if (this.embedded_view) {
44             return $.Deferred().then(this.on_loaded).resolve({fields_view: this.embedded_view});
45         } else {
46             var context = new openerp.base.CompoundContext(this.dataset.get_context());
47             if (this.view_manager.action && this.view_manager.action.context) {
48                 context.add(this.view_manager.action.context);
49             }
50             return this.rpc("/base/formview/load", {"model": this.model, "view_id": this.view_id,
51                 toolbar:!!this.flags.sidebar, context: context}, this.on_loaded);
52         }
53     },
54     on_loaded: function(data) {
55         var self = this;
56         this.fields_view = data.fields_view;
57         var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
58
59         this.$element.html(QWeb.render(this.template, { 'frame': frame, 'view': this }));
60         _.each(this.widgets, function(w) {
61             w.start();
62         });
63         this.$form_header = this.$element.find('#' + this.element_id + '_header');
64         this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
65             var action = $(this).data('pager-action');
66             self.on_pager_action(action);
67         });
68
69         this.$form_header.find('button.oe_form_button_save').click(this.do_save);
70         this.$form_header.find('button.oe_form_button_save_edit').click(this.do_save_edit);
71         this.$form_header.find('button.oe_form_button_cancel').click(this.do_cancel);
72         this.$form_header.find('button.oe_form_button_new').click(this.on_button_new);
73
74         this.view_manager.sidebar.set_toolbar(data.fields_view.toolbar);
75         this.has_been_loaded.resolve();
76     },
77     do_show: function () {
78         var self = this;
79         if (this.dataset.index === null) {
80             // null index means we should start a new record
81             this.on_button_new();
82         } else {
83             this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
84         }
85         self.$element.show();
86         this.view_manager.sidebar.do_refresh(true);
87     },
88     do_hide: function () {
89         this.$element.hide();
90     },
91     on_record_loaded: function(record) {
92         if (!record) {
93             throw("Form: No record received");
94         }
95         if (!record.id) {
96             this.$form_header.find('.oe_form_on_create').show();
97             this.$form_header.find('.oe_form_on_update').hide();
98             this.$form_header.find('button.oe_form_button_new').hide();
99         } else {
100             this.$form_header.find('.oe_form_on_create').hide();
101             this.$form_header.find('.oe_form_on_update').show();
102             this.$form_header.find('button.oe_form_button_new').show();
103         }
104         this.touched = false;
105         this.datarecord = record;
106         for (var f in this.fields) {
107             var field = this.fields[f];
108             field.touched = false;
109             field.set_value(this.datarecord[f] || false);
110             field.validate();
111         }
112         if (!record.id) {
113             // New record: Second pass in order to trigger the onchanges
114             this.touched = true;
115             this.show_invalid = false;
116             for (var f in record) {
117                 var field = this.fields[f];
118                 if (field) {
119                     field.touched = true;
120                     this.do_onchange(field);
121                 }
122             }
123         }
124         this.on_form_changed();
125         this.show_invalid = this.ready = true;
126         this.do_update_pager(record.id == null);
127         this.do_update_sidebar();
128         if (this.default_focus_field) {
129             this.default_focus_field.focus();
130         }
131     },
132     on_form_changed: function() {
133         for (var w in this.widgets) {
134             w = this.widgets[w];
135             w.process_modifiers();
136             w.update_dom();
137         }
138     },
139     on_pager_action: function(action) {
140         switch (action) {
141             case 'first':
142                 this.dataset.index = 0;
143                 break;
144             case 'previous':
145                 this.dataset.previous();
146                 break;
147             case 'next':
148                 this.dataset.next();
149                 break;
150             case 'last':
151                 this.dataset.index = this.dataset.ids.length - 1;
152                 break;
153         }
154         this.reload();
155     },
156     do_update_pager: function(hide_index) {
157         var $pager = this.$element.find('#' + this.element_id + '_header div.oe_form_pager');
158         var index = hide_index ? '-' : this.dataset.index + 1;
159         $pager.find('span.oe_pager_index').html(index);
160         $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
161     },
162     do_onchange: function(widget, processed) {
163         processed = processed || [];
164         if (widget.node.attrs.on_change) {
165             var self = this;
166             this.ready = false;
167             var onchange = _.trim(widget.node.attrs.on_change);
168             var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
169             if (call) {
170                 var method = call[1], args = [];
171                 var context_index = null;
172                 var argument_replacement = {
173                     'False' : function() {return false;},
174                     'True' : function() {return true;},
175                     'None' : function() {return null;},
176                     'context': function(i) {
177                         context_index = i;
178                         var ctx = widget.build_context ? widget.build_context() : {};
179                         return ctx;
180                     }
181                 }
182                 var parent_fields = null;
183                 _.each(call[2].split(','), function(a, i) {
184                     var field = _.trim(a);
185                     if (field in argument_replacement) {
186                         args.push(argument_replacement[field](i));
187                         return;
188                     } else if (self.fields[field]) {
189                         var value = self.fields[field].get_on_change_value();
190                         args.push(value == null ? false : value);
191                         return;
192                     } else {
193                         var splitted = field.split('.');
194                         if (splitted.length > 1 && _.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
195                             if (parent_fields === null) {
196                                 parent_fields = self.dataset.parent_view.get_fields_values();
197                             }
198                             var p_val = parent_fields[_.trim(splitted[1])];
199                             if (p_val !== undefined) {
200                                 args.push(p_val == null ? false : p_val);
201                                 return;
202                             }
203                         }
204                     }
205                     throw "Could not get field with name '" + field +
206                         "' for onchange '" + onchange + "'";
207                 });
208                 var ajax = {
209                     url: '/base/dataset/call',
210                     async: false
211                 };
212                 return this.rpc(ajax, {
213                     model: this.dataset.model,
214                     method: method,
215                     args: [(this.datarecord.id == null ? [] : [this.datarecord.id])].concat(args),
216                     context_id: context_index === null ? null : context_index + 1
217                 }, function(response) {
218                     self.on_processed_onchange(response, processed);
219                 });
220             } else {
221                 this.log("Wrong on_change format", on_change);
222             }
223         }
224     },
225     on_processed_onchange: function(response, processed) {
226         var result = response.result;
227         if (result.value) {
228             for (var f in result.value) {
229                 var field = this.fields[f];
230                 if (field) {
231                     var value = result.value[f];
232                     processed.push(field.name);
233                     if (field.get_value() != value) {
234                         field.set_value(value);
235                         field.touched = true;
236                         if (_.indexOf(processed, field.name) < 0) {
237                             this.do_onchange(field, processed);
238                         }
239                     }
240                 } else {
241                     // this is a common case, the normal behavior should be to ignore it
242                 }
243             }
244             this.on_form_changed();
245         }
246         if (!_.isEmpty(result.warning)) {
247             $(QWeb.render("DialogWarning", result.warning)).dialog({
248                 modal: true,
249                 buttons: {
250                     Ok: function() {
251                         $(this).dialog("close");
252                     }
253                 }
254             });
255         }
256         if (result.domain) {
257             // Will be removed ?
258         }
259         this.ready = true;
260     },
261     on_button_new: function() {
262         var self = this;
263         $.when(this.has_been_loaded).then(function() {
264             self.dataset.default_get(_.keys(self.fields_view.fields), function(result) {
265                 self.on_record_loaded(result.result);
266             });
267         });
268     },
269     /**
270      * Triggers saving the form's record. Chooses between creating a new
271      * record or saving an existing one depending on whether the record
272      * already has an id property.
273      *
274      * @param {Function} success callback on save success
275      * @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)
276      */
277     do_save: function(success, prepend_on_create) {
278         var self = this;
279         if (!this.ready) {
280             return false;
281         }
282         var invalid = false,
283             values = {},
284             first_invalid_field = null;
285         for (var f in this.fields) {
286             f = this.fields[f];
287             if (f.invalid) {
288                 invalid = true;
289                 f.update_dom();
290                 if (!first_invalid_field) {
291                     first_invalid_field = f;
292                 }
293             } else if (f.touched) {
294                 values[f.name] = f.get_value();
295             }
296         }
297         if (invalid) {
298             first_invalid_field.focus();
299             this.on_invalid();
300             return false;
301         } else {
302             this.log("About to save", values);
303             if (!this.datarecord.id) {
304                 this.dataset.create(values, function(r) {
305                     self.on_created(r, success, prepend_on_create);
306                 });
307             } else {
308                 this.dataset.write(this.datarecord.id, values, function(r) {
309                     self.on_saved(r, success);
310                 });
311             }
312             return true;
313         }
314     },
315     do_save_edit: function() {
316         this.do_save();
317         //this.switch_readonly(); Use promises
318     },
319     switch_readonly: function() {
320     },
321     switch_editable: function() {
322     },
323     on_invalid: function() {
324         var msg = "<ul>";
325         _.each(this.fields, function(f) {
326             if (f.invalid) {
327                 msg += "<li>" + f.string + "</li>";
328             }
329         });
330         msg += "</ul>";
331         this.notification.warn("The following fields are invalid :", msg);
332     },
333     on_saved: function(r, success) {
334         if (!r.result) {
335             this.notification.warn("Record not saved", "Problem while saving record.");
336         } else {
337             this.notification.notify("Record saved", "The record #" + this.datarecord.id + " has been saved.");
338             if (success) {
339                 success(r);
340             }
341             this.reload();
342         }
343     },
344     /**
345      * Updates the form' dataset to contain the new record:
346      *
347      * * Adds the newly created record to the current dataset (at the end by
348      *   default)
349      * * Selects that record (sets the dataset's index to point to the new
350      *   record's id).
351      * * Updates the pager and sidebar displays
352      *
353      * @param {Object} r
354      * @param {Function} success callback to execute after having updated the dataset
355      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
356      */
357     on_created: function(r, success, prepend_on_create) {
358         if (!r.result) {
359             this.notification.warn("Record not created", "Problem while creating record.");
360         } else {
361             this.datarecord.id = r.result;
362             if (!prepend_on_create) {
363                 this.dataset.ids.push(this.datarecord.id);
364                 this.dataset.index = this.dataset.ids.length - 1;
365             } else {
366                 this.dataset.ids.unshift(this.datarecord.id);
367                 this.dataset.index = 0;
368             }
369             this.do_update_pager();
370             this.do_update_sidebar();
371             this.notification.notify("Record created", "The record has been created with id #" + this.datarecord.id);
372             if (success) {
373                 success(_.extend(r, {created: true}));
374             }
375             this.reload();
376         }
377     },
378     do_search: function (domains, contexts, groupbys) {
379         this.notification.notify("Searching form");
380     },
381     on_action: function (action) {
382         this.notification.notify('Executing action ' + action);
383     },
384     do_cancel: function () {
385         this.notification.notify("Cancelling form");
386     },
387     do_update_sidebar: function() {
388         if (this.flags.sidebar === false) {
389             return;
390         }
391         if (!this.datarecord.id) {
392             this.on_attachments_loaded([]);
393         } else {
394             // TODO fme: modify this so it doesn't try to load attachments when there is not sidebar
395             /*(new openerp.base.DataSetSearch(
396                     this.session, 'ir.attachment', this.dataset.get_context(),
397                     [['res_model', '=', this.dataset.model],
398                      ['res_id', '=', this.datarecord.id],
399                      ['type', 'in', ['binary', 'url']]])).read_slice(
400                 ['name', 'url', 'type'], false, false,
401                 this.on_attachments_loaded);*/
402         }
403     },
404     on_attachments_loaded: function(attachments) {
405         this.$sidebar = this.view_manager.sidebar.$element.find('.sidebar-attachments');
406         this.attachments = attachments;
407         this.$sidebar.html(QWeb.render('FormView.sidebar.attachments', this));
408         this.$sidebar.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
409         this.$sidebar.find('.oe-binary-file').change(this.on_attachment_changed);
410     },
411     on_attachment_changed: function(e) {
412         window[this.element_id + '_iframe'] = this.do_update_sidebar;
413         var $e = $(e.target);
414         if ($e.val() != '') {
415             this.$sidebar.find('form.oe-binary-form').submit();
416             $e.parent().find('input[type=file]').attr('disabled', 'true');
417             $e.parent().find('button').attr('disabled', 'true').find('img, span').toggle();
418         }
419     },
420     on_attachment_delete: function(e) {
421         var self = this, $e = $(e.currentTarget);
422         var name = _.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
423         if (confirm("Do you really want to delete the attachment " + name + " ?")) {
424             this.rpc('/base/dataset/unlink', {
425                 model: 'ir.attachment',
426                 ids: [parseInt($e.attr('data-id'))]
427             }, function(r) {
428                 $e.parent().remove();
429                 self.notification.notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
430             });
431         }
432     },
433     reload: function() {
434         if (this.datarecord.id) {
435             this.dataset.read_index(_.keys(this.fields_view.fields), this.on_record_loaded);
436         } else {
437             this.on_button_new();
438         }
439     },
440     get_fields_values: function() {
441         var values = {};
442         _.each(this.fields, function(value, key) {
443             var val = value.get_value();
444             values[key] = val;
445         });
446         return values;
447     }
448 });
449
450 /** @namespace */
451 openerp.base.form = {};
452
453 openerp.base.form.compute_domain = function(expr, fields) {
454     var stack = [];
455     for (var i = expr.length - 1; i >= 0; i--) {
456         var ex = expr[i];
457         if (ex.length == 1) {
458             var top = stack.pop();
459             switch (ex) {
460                 case '|':
461                     stack.push(stack.pop() || top);
462                     continue;
463                 case '&':
464                     stack.push(stack.pop() && top);
465                     continue;
466                 case '!':
467                     stack.push(!top);
468                     continue;
469                 default:
470                     throw new Error('Unknown domain operator ' + ex);
471             }
472         }
473
474         var field = fields[ex[0]].get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
475         var op = ex[1];
476         var val = ex[2];
477
478         switch (op.toLowerCase()) {
479             case '=':
480             case '==':
481                 stack.push(field == val);
482                 break;
483             case '!=':
484             case '<>':
485                 stack.push(field != val);
486                 break;
487             case '<':
488                 stack.push(field < val);
489                 break;
490             case '>':
491                 stack.push(field > val);
492                 break;
493             case '<=':
494                 stack.push(field <= val);
495                 break;
496             case '>=':
497                 stack.push(field >= val);
498                 break;
499             case 'in':
500                 stack.push(_(val).contains(field));
501                 break;
502             case 'not in':
503                 stack.push(!_(val).contains(field));
504                 break;
505             default:
506                 this.log("Unsupported operator in modifiers :", op);
507         }
508     }
509     return _.all(stack);
510 };
511
512 openerp.base.form.Widget = openerp.base.Controller.extend({
513     template: 'Widget',
514     init: function(view, node) {
515         this.view = view;
516         this.node = node;
517         this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
518         this.type = this.type || node.tag;
519         this.element_name = this.element_name || this.type;
520         this.element_id = [this.view.element_id, this.element_name, this.view.widgets_counter++].join("_");
521
522         this._super(this.view.session, this.element_id);
523
524         this.view.widgets[this.element_id] = this;
525         this.children = node.children;
526         this.colspan = parseInt(node.attrs.colspan || 1);
527
528         this.string = this.string || node.attrs.string;
529         this.help = this.help || node.attrs.help;
530         this.invisible = this.modifiers['invisible'] === true;
531     },
532     start: function() {
533         this.$element = $('#' + this.element_id);
534     },
535     process_modifiers: function() {
536         var compute_domain = openerp.base.form.compute_domain;
537         for (var a in this.modifiers) {
538             this[a] = compute_domain(this.modifiers[a], this.view.fields);
539         }
540     },
541     update_dom: function() {
542         this.$element.toggle(!this.invisible);
543     },
544     render: function() {
545         var template = this.template;
546         return QWeb.render(template, { "widget": this });
547     }
548 });
549
550 openerp.base.form.WidgetFrame = openerp.base.form.Widget.extend({
551     template: 'WidgetFrame',
552     init: function(view, node) {
553         this._super(view, node);
554         this.columns = node.attrs.col || 4;
555         this.x = 0;
556         this.y = 0;
557         this.table = [];
558         this.add_row();
559         for (var i = 0; i < node.children.length; i++) {
560             var n = node.children[i];
561             if (n.tag == "newline") {
562                 this.add_row();
563             } else {
564                 this.handle_node(n);
565             }
566         }
567         this.set_row_cells_with(this.table[this.table.length - 1]);
568     },
569     add_row: function(){
570         if (this.table.length) {
571             this.set_row_cells_with(this.table[this.table.length - 1]);
572         }
573         var row = [];
574         this.table.push(row);
575         this.x = 0;
576         this.y += 1;
577         return row;
578     },
579     set_row_cells_with: function(row) {
580         for (var i = 0; i < row.length; i++) {
581             var w = row[i];
582             if (w.is_field_label) {
583                 w.width = "1%";
584                 if (row[i + 1]) {
585                     row[i + 1].width = Math.round((100 / this.columns) * (w.colspan + 1) - 1) + '%';
586                 }
587             } else if (w.width === undefined) {
588                 w.width = Math.round((100 / this.columns) * w.colspan) + '%';
589             }
590         }
591     },
592     handle_node: function(node) {
593         var type = {};
594         if (node.tag == 'field') {
595             type = this.view.fields_view.fields[node.attrs.name] || {};
596         }
597         var widget = new (this.view.registry.get_any(
598                 [node.attrs.widget, type.type, node.tag])) (this.view, node);
599         if (node.tag == 'field') {
600             if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
601                 this.view.default_focus_field = widget;
602             }
603             if (node.attrs.nolabel != '1') {
604                 var label = new (this.view.registry.get_object('label')) (this.view, node);
605                 label["for"] = widget;
606                 this.add_widget(label);
607             }
608         }
609         this.add_widget(widget);
610     },
611     add_widget: function(widget) {
612         var current_row = this.table[this.table.length - 1];
613         if (current_row.length && (this.x + widget.colspan) > this.columns) {
614             current_row = this.add_row();
615         }
616         current_row.push(widget);
617         this.x += widget.colspan;
618         return widget;
619     }
620 });
621
622 openerp.base.form.WidgetNotebook = openerp.base.form.Widget.extend({
623     template: 'WidgetNotebook',
624     init: function(view, node) {
625         this._super(view, node);
626         this.pages = [];
627         for (var i = 0; i < node.children.length; i++) {
628             var n = node.children[i];
629             if (n.tag == "page") {
630                 var page = new openerp.base.form.WidgetNotebookPage(this.view, n, this, this.pages.length);
631                 this.pages.push(page);
632             }
633         }
634     },
635     start: function() {
636         this._super.apply(this, arguments);
637         this.$element.tabs();
638     }
639 });
640
641 openerp.base.form.WidgetNotebookPage = openerp.base.form.WidgetFrame.extend({
642     template: 'WidgetNotebookPage',
643     init: function(view, node, notebook, index) {
644         this.notebook = notebook;
645         this.index = index;
646         this.element_name = 'page_' + index;
647         this._super(view, node);
648         this.element_tab_id = this.element_id + '_tab';
649     },
650     start: function() {
651         this._super.apply(this, arguments);
652         this.$element_tab = $('#' + this.element_tab_id);
653     },
654     update_dom: function() {
655         if (this.invisible) {
656             this.notebook.$element.tabs('select', 0);
657         }
658         this.$element_tab.toggle(!this.invisible);
659         this.$element.toggle(!this.invisible);
660     }
661 });
662
663 openerp.base.form.WidgetSeparator = openerp.base.form.Widget.extend({
664     init: function(view, node) {
665         this._super(view, node);
666         this.template = "WidgetSeparator";
667     }
668 });
669
670 openerp.base.form.WidgetButton = openerp.base.form.Widget.extend({
671     init: function(view, node) {
672         this._super(view, node);
673         this.template = "WidgetButton";
674         if (node.attrs.default_focus == '1') {
675             // TODO fme: provide enter key binding to widgets
676             this.view.default_focus_button = this;
677         }
678     },
679     start: function() {
680         this._super.apply(this, arguments);
681         this.$element.click(this.on_click);
682     },
683     on_click: function(saved) {
684         var self = this;
685         if (!this.node.attrs.special && this.view.touched && saved !== true) {
686             this.view.do_save(function() {
687                 self.on_click(true);
688             });
689         } else {
690             if (this.node.attrs.confirm) {
691                 var dialog = $('<div>' + this.node.attrs.confirm + '</div>').dialog({
692                     title: 'Confirm',
693                     modal: true,
694                     buttons: {
695                         Ok: function() {
696                             self.on_confirmed();
697                             $(this).dialog("close");
698                         },
699                         Cancel: function() {
700                             $(this).dialog("close");
701                         }
702                     }
703                 });
704             } else {
705                 this.on_confirmed();
706             }
707         }
708     },
709     on_confirmed: function() {
710         var self = this;
711
712         this.view.execute_action(
713             this.node.attrs, this.view.dataset, this.session.action_manager,
714             this.view.datarecord.id, function (result) {
715                 self.log("Button returned", result);
716                 self.view.reload();
717             }, function() {
718                 self.view.reload();
719             });
720     }
721 });
722
723 openerp.base.form.WidgetLabel = openerp.base.form.Widget.extend({
724     init: function(view, node) {
725         this.element_name = 'label_' + node.attrs.name;
726
727         this._super(view, node);
728
729         // TODO fme: support for attrs.align
730         if (this.node.tag == 'label' && this.node.attrs.colspan) {
731             this.is_field_label = false;
732             this.template = "WidgetParagraph";
733         } else {
734             this.is_field_label = true;
735             this.template = "WidgetLabel";
736         }
737         this.colspan = 1;
738     },
739     render: function () {
740         if (this['for'] && this.type !== 'label') {
741             return QWeb.render(this.template, {widget: this['for']});
742         }
743         // Actual label widgets should not have a false and have type label
744         return QWeb.render(this.template, {widget: this});
745     }
746 });
747
748 openerp.base.form.Field = openerp.base.form.Widget.extend({
749     init: function(view, node) {
750         this.name = node.attrs.name;
751         this.value = undefined;
752         view.fields[this.name] = this;
753         this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
754         this.element_name = "field_" + this.name + "_" + this.type;
755
756         this._super(view, node);
757
758         if (node.attrs.nolabel != '1' && this.colspan > 1) {
759             this.colspan--;
760         }
761         this.field = view.fields_view.fields[node.attrs.name] || {};
762         this.string = node.attrs.string || this.field.string;
763         this.help = node.attrs.help || this.field.help;
764         this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
765         this.readonly = this.modifiers['readonly'] === true;
766         this.required = this.modifiers['required'] === true;
767         this.invalid = false;
768         this.touched = false;
769     },
770     set_value: function(value) {
771         this.value = value;
772         this.invalid = false;
773         this.update_dom();
774     },
775     set_value_from_ui: function() {
776         this.value = undefined;
777     },
778     get_value: function() {
779         return this.value;
780     },
781     get_on_change_value: function() {
782         return this.get_value();
783     },
784     update_dom: function() {
785         this._super.apply(this, arguments);
786         this.$element.toggleClass('disabled', this.readonly);
787         this.$element.toggleClass('required', this.required);
788         if (this.view.show_invalid) {
789             this.$element.toggleClass('invalid', this.invalid);
790         }
791     },
792     on_ui_change: function() {
793         this.touched = this.view.touched = true;
794         this.validate();
795         if (!this.invalid) {
796             this.set_value_from_ui();
797             this.view.do_onchange(this);
798             this.view.on_form_changed();
799         } else {
800             this.update_dom();
801         }
802     },
803     validate: function() {
804         this.invalid = false;
805     },
806     focus: function() {
807     },
808     _build_view_fields_values: function() {
809         var a_dataset = this.view.dataset || {};
810         var fields_values = this.view.get_fields_values();
811         var parent_values = a_dataset.parent_view ? a_dataset.parent_view.get_fields_values() : {};
812         fields_values.parent = parent_values;
813         return fields_values;
814     },
815     /**
816      * Builds a new context usable for operations related to fields by merging
817      * the fields'context with the action's context.
818      */
819     build_context: function() {
820         var a_context = this.view.dataset.get_context() || {};
821         var f_context = this.field.context || {};
822         var v_context1 = this.node.attrs.default_get || {};
823         var v_context2 = this.node.attrs.context || {};
824         var v_context = new openerp.base.CompoundContext(v_context1, v_context2);
825         if (v_context1.__ref || v_context2.__ref || true) { //TODO niv: remove || true
826             var fields_values = this._build_view_fields_values();
827             v_context.set_eval_context(fields_values);
828         }
829         var ctx = new openerp.base.CompoundContext(a_context, f_context, v_context);
830         return ctx;
831     },
832     build_domain: function() {
833         var f_domain = this.field.domain || [];
834         var v_domain = this.node.attrs.domain || [];
835         if (!(v_domain instanceof Array) || true) { //TODO niv: remove || true
836             var fields_values = this._build_view_fields_values();
837             v_domain = new openerp.base.CompoundDomain(v_domain).set_eval_context(fields_values);
838         }
839         return new openerp.base.CompoundDomain(f_domain, v_domain);
840     }
841 });
842
843 openerp.base.form.FieldChar = openerp.base.form.Field.extend({
844     init: function(view, node) {
845         this._super(view, node);
846         this.template = "FieldChar";
847     },
848     start: function() {
849         this._super.apply(this, arguments);
850         this.$element.find('input').change(this.on_ui_change);
851     },
852     set_value: function(value) {
853         this._super.apply(this, arguments);
854         var show_value = (value != null && value !== false) ? value : '';
855         this.$element.find('input').val(show_value);
856     },
857     update_dom: function() {
858         this._super.apply(this, arguments);
859         this.$element.find('input').attr('disabled', this.readonly);
860     },
861     set_value_from_ui: function() {
862         this.value = this.$element.find('input').val();
863     },
864     validate: function() {
865         this.invalid = false;
866         var value = this.$element.find('input').val();
867         if (value === "") {
868             this.invalid = this.required;
869         } else if (this.validation_regex) {
870             this.invalid = !this.validation_regex.test(value);
871         }
872     },
873     focus: function() {
874         this.$element.find('input').focus();
875     }
876 });
877
878 openerp.base.form.FieldEmail = openerp.base.form.FieldChar.extend({
879     init: function(view, node) {
880         this._super(view, node);
881         this.template = "FieldEmail";
882         this.validation_regex = /@/;
883     },
884     start: function() {
885         this._super.apply(this, arguments);
886         this.$element.find('button').click(this.on_button_clicked);
887     },
888     on_button_clicked: function() {
889         if (!this.value || this.invalid) {
890             this.notification.warn("E-mail error", "Can't send email to invalid e-mail address");
891         } else {
892             location.href = 'mailto:' + this.value;
893         }
894     },
895     set_value: function(value) {
896         this._super.apply(this, arguments);
897         var show_value = (value != null && value !== false) ? value : '';
898         this.$element.find('a').attr('href', 'mailto:' + show_value);
899     }
900 });
901
902 openerp.base.form.FieldUrl = openerp.base.form.FieldChar.extend({
903     init: function(view, node) {
904         this._super(view, node);
905         this.template = "FieldUrl";
906     },
907     start: function() {
908         this._super.apply(this, arguments);
909         this.$element.find('button').click(this.on_button_clicked);
910     },
911     on_button_clicked: function() {
912         if (!this.value) {
913             this.notification.warn("Resource error", "This resource is empty");
914         } else {
915             window.open(this.value);
916         }
917     }
918 });
919
920 openerp.base.form.FieldFloat = openerp.base.form.FieldChar.extend({
921     init: function(view, node) {
922         this._super(view, node);
923         this.validation_regex = /^-?\d+(\.\d+)?$/;
924     },
925     set_value: function(value) {
926         this._super.apply(this, [value]);
927         if (value === false || value === undefined) {
928             // As in GTK client, floats default to 0
929             value = 0;
930             this.touched = true;
931         }
932         var show_value = value.toFixed(2);
933         this.$element.find('input').val(show_value);
934     },
935     set_value_from_ui: function() {
936         this.value = Number(this.$element.find('input').val().replace(/,/g, '.'));
937     }
938 });
939
940 openerp.base.form.FieldInteger = openerp.base.form.FieldFloat.extend({
941     init: function(view, node) {
942         this._super(view, node);
943         this.validation_regex = /^-?\d+$/;
944     },
945     set_value: function(value) {
946         this._super.apply(this, [value]);
947         if (value === false || value === undefined) {
948             // TODO fme: check if GTK client default integers to 0 (like it does with floats)
949             value = 0;
950             this.touched = true;
951         }
952         var show_value = parseInt(value, 10);
953         this.$element.find('input').val(show_value);
954     },
955     set_value_from_ui: function() {
956         this.value = Number(this.$element.find('input').val());
957     }
958 });
959
960 openerp.base.form.FieldDatetime = openerp.base.form.Field.extend({
961     init: function(view, node) {
962         this._super(view, node);
963         this.template = "FieldDate";
964         this.jqueryui_object = 'datetimepicker';
965         this.validation_regex = /^\d+-\d+-\d+( \d+:\d+(:\d+)?)?$/;
966     },
967     start: function() {
968         this._super.apply(this, arguments);
969         this.$element.find('input').change(this.on_ui_change)[this.jqueryui_object]({
970             dateFormat: 'yy-mm-dd',
971             timeFormat: 'hh:mm:ss',
972             showOn: 'button',
973             buttonImage: '/base/static/src/img/ui/field_calendar.png',
974             buttonImageOnly: true,
975             constrainInput: false
976         });
977     },
978     set_value: function(value) {
979         this._super.apply(this, arguments);
980         if (!value) {
981             this.$element.find('input').val('');
982         } else {
983             this.$element.find('input').unbind('change');
984             // jQuery UI date picker wrongly call on_change event herebelow
985             this.$element.find('input')[this.jqueryui_object]('setDate', this.parse(value));
986             this.$element.find('input').change(this.on_ui_change);
987         }
988     },
989     set_value_from_ui: function() {
990         this.value = this.$element.find('input')[this.jqueryui_object]('getDate') || false;
991         if (this.value) {
992             this.value = this.format(this.value);
993         }
994     },
995     update_dom: function() {
996         this._super.apply(this, arguments);
997         this.$element.find('input').datepicker(this.readonly ? 'disable' : 'enable');
998     },
999     validate: function() {
1000         this.invalid = false;
1001         var value = this.$element.find('input').val();
1002         if (value === "") {
1003             this.invalid = this.required;
1004         } else if (this.validation_regex) {
1005             this.invalid = !this.validation_regex.test(value);
1006         } else {
1007             this.invalid = !this.$element.find('input')[this.jqueryui_object]('getDate');
1008         }
1009     },
1010     focus: function() {
1011         this.$element.find('input').focus();
1012     },
1013     parse: openerp.base.parse_datetime,
1014     format: openerp.base.format_datetime
1015 });
1016
1017 openerp.base.form.FieldDate = openerp.base.form.FieldDatetime.extend({
1018     init: function(view, node) {
1019         this._super(view, node);
1020         this.jqueryui_object = 'datepicker';
1021         this.validation_regex = /^\d+-\d+-\d+$/;
1022     },
1023     parse: openerp.base.parse_date,
1024     format: openerp.base.format_date
1025 });
1026
1027 openerp.base.form.FieldFloatTime = openerp.base.form.FieldChar.extend({
1028     init: function(view, node) {
1029         this._super(view, node);
1030         this.validation_regex = /^\d+:\d+$/;
1031     },
1032     set_value: function(value) {
1033         this._super.apply(this, [value]);
1034         if (value === false || value === undefined) {
1035             // As in GTK client, floats default to 0
1036             value = 0;
1037             this.touched = true;
1038         }
1039         var show_value = _.sprintf("%02d:%02d", Math.floor(value), Math.round((value % 1) * 60));
1040         this.$element.find('input').val(show_value);
1041     },
1042     set_value_from_ui: function() {
1043         var time = this.$element.find('input').val().split(':');
1044         this.set_value(parseInt(time[0], 10) + parseInt(time[1], 10) / 60);
1045     }
1046 });
1047
1048 openerp.base.form.FieldText = openerp.base.form.Field.extend({
1049     init: function(view, node) {
1050         this._super(view, node);
1051         this.template = "FieldText";
1052         this.validation_regex = null;
1053     },
1054     start: function() {
1055         this._super.apply(this, arguments);
1056         this.$element.find('textarea').change(this.on_ui_change);
1057     },
1058     set_value: function(value) {
1059         this._super.apply(this, arguments);
1060         var show_value = (value != null && value !== false) ? value : '';
1061         this.$element.find('textarea').val(show_value);
1062     },
1063     update_dom: function() {
1064         this._super.apply(this, arguments);
1065         this.$element.find('textarea').attr('disabled', this.readonly);
1066     },
1067     set_value_from_ui: function() {
1068         this.value = this.$element.find('textarea').val();
1069     },
1070     validate: function() {
1071         this.invalid = false;
1072         var value = this.$element.find('textarea').val();
1073         if (value === "") {
1074             this.invalid = this.required;
1075         } else if (this.validation_regex) {
1076             this.invalid = !this.validation_regex.test(value);
1077         }
1078     },
1079     focus: function() {
1080         this.$element.find('textarea').focus();
1081     }
1082 });
1083
1084 openerp.base.form.FieldBoolean = openerp.base.form.Field.extend({
1085     init: function(view, node) {
1086         this._super(view, node);
1087         this.template = "FieldBoolean";
1088     },
1089     start: function() {
1090         var self = this;
1091         this._super.apply(this, arguments);
1092         this.$element.find('input').click(function() {
1093             if ($(this).is(':checked') != self.value) {
1094                 self.on_ui_change();
1095             }
1096         });
1097     },
1098     set_value: function(value) {
1099         this._super.apply(this, arguments);
1100         this.$element.find('input')[0].checked = value;
1101     },
1102     set_value_from_ui: function() {
1103         this.value = this.$element.find('input').is(':checked');
1104     },
1105     update_dom: function() {
1106         this._super.apply(this, arguments);
1107         this.$element.find('input').attr('disabled', this.readonly);
1108     },
1109     validate: function() {
1110         this.invalid = this.required && !this.$element.find('input').is(':checked');
1111     },
1112     focus: function() {
1113         this.$element.find('input').focus();
1114     }
1115 });
1116
1117 openerp.base.form.FieldProgressBar = openerp.base.form.Field.extend({
1118     init: function(view, node) {
1119         this._super(view, node);
1120         this.template = "FieldProgressBar";
1121     },
1122     start: function() {
1123         this._super.apply(this, arguments);
1124         this.$element.find('div').progressbar({
1125             value: this.value,
1126             disabled: this.readonly
1127         });
1128     },
1129     set_value: function(value) {
1130         this._super.apply(this, arguments);
1131         var show_value = Number(value);
1132         if (isNaN(show_value)) {
1133             show_value = 0;
1134         }
1135         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(show_value + '%');
1136     }
1137 });
1138
1139 openerp.base.form.FieldTextXml = openerp.base.form.Field.extend({
1140 // to replace view editor
1141 });
1142
1143 openerp.base.form.FieldSelection = openerp.base.form.Field.extend({
1144     init: function(view, node) {
1145         this._super(view, node);
1146         this.template = "FieldSelection";
1147         this.field_index = _.map(this.field.selection, function(x, index) {
1148             return {"ikey": "" + index, "ekey": x[0], "label": x[1]};
1149         });
1150     },
1151     start: function() {
1152         // Flag indicating whether we're in an event chain containing a change
1153         // event on the select, in order to know what to do on keyup[RETURN]:
1154         // * If the user presses [RETURN] as part of changing the value of a
1155         //   selection, we should just let the value change and not let the
1156         //   event broadcast further (e.g. to validating the current state of
1157         //   the form in editable list view, which would lead to saving the
1158         //   current row or switching to the next one)
1159         // * If the user presses [RETURN] with a select closed (side-effect:
1160         //   also if the user opened the select and pressed [RETURN] without
1161         //   changing the selected value), takes the action as validating the
1162         //   row
1163         var ischanging = false;
1164         this._super.apply(this, arguments);
1165         this.$element.find('select')
1166             .change(this.on_ui_change)
1167             .change(function () { ischanging = true; })
1168             .click(function () { ischanging = false; })
1169             .keyup(function (e) {
1170                 if (e.which !== 13 || !ischanging) { return; }
1171                 e.stopPropagation();
1172                 ischanging = false;
1173             });
1174     },
1175     set_value: function(value) {
1176         value = value === null ? false : value;
1177         value = value instanceof Array ? value[0] : value;
1178         this._super(value);
1179         var option = _.detect(this.field_index, function(x) {return x.ekey === value;});
1180         this.$element.find('select').val(option === undefined ? '' : option.ikey);
1181     },
1182     set_value_from_ui: function() {
1183         var ikey = this.$element.find('select').val();
1184         var option = _.detect(this.field_index, function(x) {return x.ikey === ikey;});
1185         this.value = option === undefined ? false : option.ekey;
1186     },
1187     update_dom: function() {
1188         this._super.apply(this, arguments);
1189         this.$element.find('select').attr('disabled', this.readonly);
1190     },
1191     validate: function() {
1192         var ikey = this.$element.find('select').val();
1193         var option = _.detect(this.field_index, function(x) {return x.ikey === ikey;});
1194         this.invalid = this.required && (option === undefined || option.ekey === false);
1195     },
1196     focus: function() {
1197         this.$element.find('select').focus();
1198     }
1199 });
1200
1201 // jquery autocomplete tweak to allow html
1202 (function() {
1203     var proto = $.ui.autocomplete.prototype,
1204         initSource = proto._initSource;
1205
1206     function filter( array, term ) {
1207         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1208         return $.grep( array, function(value) {
1209             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1210         });
1211     }
1212
1213     $.extend( proto, {
1214         _initSource: function() {
1215             if ( this.options.html && $.isArray(this.options.source) ) {
1216                 this.source = function( request, response ) {
1217                     response( filter( this.options.source, request.term ) );
1218                 };
1219             } else {
1220                 initSource.call( this );
1221             }
1222         },
1223
1224         _renderItem: function( ul, item) {
1225             return $( "<li></li>" )
1226                 .data( "item.autocomplete", item )
1227                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1228                 .appendTo( ul );
1229         }
1230     });
1231 })();
1232
1233 openerp.base.form.FieldMany2One = openerp.base.form.Field.extend({
1234     init: function(view, node) {
1235         this._super(view, node);
1236         this.template = "FieldMany2One";
1237         this.limit = 7;
1238         this.value = null;
1239         this.cm_id = _.uniqueId('m2o_cm_');
1240         this.last_search = [];
1241         this.tmp_value = undefined;
1242     },
1243     start: function() {
1244         this._super();
1245         var self = this;
1246         this.$input = this.$element.find("input");
1247         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1248         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1249
1250         // context menu
1251         var bindings = {};
1252         bindings[this.cm_id + "_search"] = function() {
1253             self._search_create_popup("search");
1254         };
1255         bindings[this.cm_id + "_create"] = function() {
1256             self._search_create_popup("form");
1257         };
1258         bindings[this.cm_id + "_open"] = function() {
1259             if (!self.value) {
1260                 return;
1261             }
1262             self.session.action_manager.do_action({
1263                 "res_model": self.field.relation,
1264                 "views":[[false,"form"]],
1265                 "res_id": self.value[0],
1266                 "type":"ir.actions.act_window",
1267                 "target":"new",
1268                 "context": self.build_context()
1269             });
1270         };
1271         var cmenu = this.$menu_btn.contextMenu(this.cm_id, {'leftClickToo': true,
1272             bindings: bindings, itemStyle: {"color": ""},
1273             onContextMenu: function() {
1274                 if(self.value) {
1275                     $("#" + self.cm_id + "_open").removeClass("oe-m2o-disabled-cm");
1276                 } else {
1277                     $("#" + self.cm_id + "_open").addClass("oe-m2o-disabled-cm");
1278                 }
1279                 return true;
1280             }
1281         });
1282
1283         // some behavior for input
1284         this.$input.keyup(function() {
1285             if (self.$input.val() === "") {
1286                 self._change_int_value(null);
1287             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1288                 self._change_int_value(undefined);
1289             }
1290         });
1291         this.$drop_down.click(function() {
1292             if (self.$input.autocomplete("widget").is(":visible")) {
1293                 self.$input.autocomplete("close");
1294             } else {
1295                 if (self.value) {
1296                     self.$input.autocomplete("search", "");
1297                 } else {
1298                     self.$input.autocomplete("search");
1299                 }
1300                 self.$input.focus();
1301             }
1302         });
1303         var anyoneLoosesFocus = function() {
1304             if (!self.$input.is(":focus") &&
1305                     !self.$input.autocomplete("widget").is(":visible") &&
1306                     !self.value) {
1307                 if(self.value === undefined && self.last_search.length > 0) {
1308                     self._change_int_ext_value(self.last_search[0]);
1309                 } else {
1310                     self._change_int_ext_value(null);
1311                 }
1312             }
1313         }
1314         this.$input.focusout(anyoneLoosesFocus);
1315
1316         // autocomplete
1317         this.$input.autocomplete({
1318             source: function(req, resp) { self.get_search_result(req, resp); },
1319             select: function(event, ui) {
1320                 var item = ui.item;
1321                 if (item.id) {
1322                     self._change_int_value([item.id, item.name]);
1323                 } else if (item.action) {
1324                     self._change_int_value(undefined);
1325                     item.action();
1326                     return false;
1327                 }
1328             },
1329             focus: function(e, ui) {
1330                 e.preventDefault();
1331             },
1332             html: true,
1333             close: anyoneLoosesFocus,
1334             minLength: 0,
1335             delay: 0
1336         });
1337     },
1338     // autocomplete component content handling
1339     get_search_result: function(request, response) {
1340         var search_val = request.term;
1341         var self = this;
1342
1343         var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1344
1345         dataset.name_search(search_val, self.build_domain(), 'ilike',
1346                 this.limit + 1, function(data) {
1347             self.last_search = data.result;
1348             // possible selections for the m2o
1349             var values = _.map(data.result, function(x) {
1350                 return {label: $('<span />').text(x[1]).html(), name:x[1], id:x[0]};
1351             });
1352
1353             // search more... if more results that max
1354             if (values.length > self.limit) {
1355                 values = values.slice(0, self.limit);
1356                 values.push({label: "<em>   Search More...</em>", action: function() {
1357                     dataset.name_search(search_val, self.build_domain(), 'ilike'
1358                     , false, function(data) {
1359                         self._change_int_value(null);
1360                         self._search_create_popup("search", data.result);
1361                     });
1362                 }});
1363             }
1364             // quick create
1365             var raw_result = _(data.result).map(function(x) {return x[1];})
1366             if (search_val.length > 0 &&
1367                 !_.include(raw_result, search_val) &&
1368                 (!self.value || search_val !== self.value[1])) {
1369                 values.push({label: '<em>   Create "<strong>' +
1370                         $('<span />').text(search_val).html() + '</strong>"</em>', action: function() {
1371                     self._quick_create(search_val);
1372                 }});
1373             }
1374             // create...
1375             values.push({label: "<em>   Create and Edit...</em>", action: function() {
1376                 self._change_int_value(null);
1377                 self._search_create_popup("form", undefined, {"default_name": search_val});
1378             }});
1379
1380             response(values);
1381         });
1382     },
1383     _quick_create: function(name) {
1384         var self = this;
1385         var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1386         dataset.name_create(name, function(data) {
1387             self._change_int_ext_value(data.result);
1388         }).fail(function(error, event) {
1389             event.preventDefault();
1390             self._change_int_value(null);
1391             self._search_create_popup("form", undefined, {"default_name": name});
1392         });
1393     },
1394     // all search/create popup handling
1395     _search_create_popup: function(view, ids, context) {
1396         var self = this;
1397         var pop = new openerp.base.form.SelectCreatePopup(null, self.view.session);
1398         pop.select_element(self.field.relation,{
1399                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
1400                 initial_view: view,
1401                 disable_multiple_selection: true
1402                 }, self.build_domain(),
1403                 new openerp.base.CompoundContext(self.build_context(), context || {}));
1404         pop.on_select_elements.add(function(element_ids) {
1405             var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1406             dataset.name_get([element_ids[0]], function(data) {
1407                 self._change_int_ext_value(data.result[0]);
1408                 pop.stop();
1409             });
1410         });
1411     },
1412     _change_int_ext_value: function(value) {
1413         this._change_int_value(value);
1414         this.$input.val(this.value ? this.value[1] : "");
1415     },
1416     _change_int_value: function(value) {
1417         this.value = value;
1418         var back_orig_value = this.original_value;
1419         if (this.value === null || this.value) {
1420             this.original_value = this.value;
1421         }
1422         if (back_orig_value === undefined) { // first use after a set_value()
1423             return;
1424         }
1425         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
1426                 !== (this.value ? this.value[0] : null))) {
1427             this.on_ui_change();
1428         }
1429     },
1430     set_value_from_ui: function() {},
1431     set_value: function(value) {
1432         value = value || null;
1433         var self = this;
1434         var _super = this._super;
1435         this.tmp_value = value;
1436         var real_set_value = function(rval) {
1437             self.tmp_value = undefined;
1438             _super.apply(self, rval);
1439             self.original_value = undefined;
1440             self._change_int_ext_value(rval);
1441         };
1442         if(typeof(value) === "number") {
1443             var dataset = new openerp.base.DataSetStatic(this.session, this.field.relation, self.build_context());
1444             dataset.name_get([value], function(data) {
1445                 real_set_value(data.result[0]);
1446             }).fail(function() {self.tmp_value = undefined;});
1447         } else {
1448             setTimeout(function() {real_set_value(value);}, 0);
1449         }
1450     },
1451     get_value: function() {
1452         if (this.tmp_value !== undefined) {
1453             if (this.tmp_value instanceof Array) {
1454                 return this.tmp_value[0];
1455             }
1456             return this.tmp_value ? this.tmp_value : false;
1457         }
1458         if (this.value === undefined)
1459             return this.original_value ? this.original_value[0] : false;
1460         return this.value ? this.value[0] : false;
1461     },
1462     validate: function() {
1463         this.invalid = false;
1464         if (this.value === null) {
1465             this.invalid = this.required;
1466         }
1467     }
1468 });
1469
1470 /*
1471 # Values: (0, 0,  { fields })    create
1472 #         (1, ID, { fields })    update
1473 #         (2, ID)                remove (delete)
1474 #         (3, ID)                unlink one (target id or target of relation)
1475 #         (4, ID)                link
1476 #         (5)                    unlink all (only valid for one2many)
1477 */
1478 var commands = {
1479     // (0, _, {values})
1480     CREATE: 0,
1481     'create': function (values) {
1482         return [commands.CREATE, false, values];
1483     },
1484     // (1, id, {values})
1485     UPDATE: 1,
1486     'update': function (id, values) {
1487         return [commands.UPDATE, id, values];
1488     },
1489     // (2, id[, _])
1490     DELETE: 2,
1491     'delete': function (id) {
1492         return [commands.DELETE, id, false];
1493     },
1494     // (3, id[, _]) removes relation, but not linked record itself
1495     FORGET: 3,
1496     'forget': function (id) {
1497         return [commands.FORGET, id, false];
1498     },
1499     // (4, id[, _])
1500     LINK_TO: 4,
1501     'link_to': function (id) {
1502         return [commands.LINK_TO, id, false];
1503     },
1504     // (5[, _[, _]])
1505     DELETE_ALL: 5,
1506     'delete_all': function () {
1507         return [5, false, false];
1508     },
1509     // (6, _, ids) replaces all linked records with provided ids
1510     REPLACE_WITH: 6,
1511     'replace_with': function (ids) {
1512         return [6, false, ids];
1513     }
1514 };
1515 openerp.base.form.FieldOne2Many = openerp.base.form.Field.extend({
1516     multi_selection: false,
1517     init: function(view, node) {
1518         this._super(view, node);
1519         this.template = "FieldOne2Many";
1520         this.is_started = $.Deferred();
1521     },
1522     start: function() {
1523         this._super.apply(this, arguments);
1524
1525         var self = this;
1526
1527         this.dataset = new openerp.base.form.One2ManyDataSet(this.session, this.field.relation);
1528         this.dataset.o2m = this;
1529         this.dataset.parent_view = this.view;
1530         this.dataset.on_change.add_last(function() {
1531             self.on_ui_change();
1532         });
1533
1534         var modes = this.node.attrs.mode;
1535         modes = !!modes ? modes.split(",") : ["tree", "form"];
1536         var views = [];
1537         _.each(modes, function(mode) {
1538             var view = {view_id: false, view_type: mode == "tree" ? "list" : mode};
1539             if (self.field.views && self.field.views[mode]) {
1540                 view.embedded_view = self.field.views[mode];
1541             }
1542             if(view.view_type === "list") {
1543                 view.options = {
1544                     'selectable': self.multi_selection
1545                 };
1546             }
1547             views.push(view);
1548         });
1549         this.views = views;
1550
1551         this.viewmanager = new openerp.base.ViewManager(this.view.session,
1552             this.element_id, this.dataset, views);
1553         this.viewmanager.registry = openerp.base.views.clone({
1554             list: 'openerp.base.form.One2ManyListView'
1555         });
1556
1557         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
1558             if (view_type == "list") {
1559                 controller.o2m = self;
1560             } else if (view_type == "form") {
1561                 // TODO niv
1562             }
1563             self.is_started.resolve();
1564         });
1565         setTimeout(function () {
1566             self.viewmanager.start();
1567         }, 0);
1568     },
1569     reload_current_view: function() {
1570         var self = this;
1571         var view = self.viewmanager.views[self.viewmanager.active_view].controller;
1572         if(self.viewmanager.active_view === "list") {
1573             view.reload_content();
1574         } else if (self.viewmanager.active_view === "form") {
1575             // TODO niv: implement
1576         }
1577     },
1578     set_value_from_ui: function() {},
1579     set_value: function(value) {
1580         value = value || [];
1581         var self = this;
1582         this.dataset.reset_ids([]);
1583         if(value.length >= 1 && value[0] instanceof Array) {
1584             var ids = [];
1585             _.each(value, function(command) {
1586                 var obj = {values: command[2]};
1587                 switch (command[0]) {
1588                     case commands.CREATE:
1589                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1590                         self.dataset.to_create.push(obj);
1591                         self.dataset.cache.push(_.clone(obj));
1592                         ids.push(obj.id);
1593                         return;
1594                     case commands.UPDATE:
1595                         obj['id'] = command[1];
1596                         self.dataset.to_write.push(obj);
1597                         self.dataset.cache.push(_.clone(obj));
1598                         ids.push(obj.id);
1599                         return;
1600                     case commands.DELETE:
1601                         self.dataset.to_delete.push({id: command[1]});
1602                         return;
1603                     case commands.LINK_TO:
1604                         ids.push(command[1]);
1605                         return;
1606                     case commands.DELETE_ALL:
1607                         self.dataset.delete_all = true;
1608                         return;
1609                 }
1610             });
1611             this._super(ids);
1612             this.dataset.set_ids(ids);
1613         } else if (value.length >= 1 && typeof(value[0]) === "object") {
1614             var ids = [];
1615             this.dataset.delete_all = true;
1616             _.each(value, function(command) {
1617                 var obj = {values: command};
1618                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
1619                 self.dataset.to_create.push(obj);
1620                 self.dataset.cache.push(_.clone(obj));
1621                 ids.push(obj.id);
1622             });
1623             this._super(ids);
1624             this.dataset.set_ids(ids);
1625         } else {
1626             this._super(value);
1627             this.dataset.reset_ids(value);
1628         }
1629         $.when(this.is_started).then(function() {
1630             self.reload_current_view();
1631         });
1632     },
1633     get_value: function() {
1634         var self = this;
1635         if (!this.dataset)
1636             return [];
1637         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
1638         val = val.concat(_.map(this.dataset.ids, function(id) {
1639             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
1640             if (alter_order) {
1641                 return commands.create(alter_order.values);
1642             }
1643             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
1644             if (alter_order) {
1645                 return commands.update(alter_order.id, alter_order.values);
1646             }
1647             return commands.link_to(id);
1648         }));
1649         return val.concat(_.map(
1650             this.dataset.to_delete, function(x) {
1651                 return commands['delete'](x.id);}));
1652     },
1653     validate: function() {
1654         this.invalid = false;
1655         // TODO niv
1656     }
1657 });
1658
1659 openerp.base.form.One2ManyDataSet = openerp.base.BufferedDataSet.extend({
1660     get_context: function() {
1661         this.context = this.o2m.build_context();
1662         return this.context;
1663     }
1664 });
1665
1666 openerp.base.form.One2ManyListView = openerp.base.ListView.extend({
1667     do_add_record: function () {
1668         if (this.options.editable) {
1669             this._super.apply(this, arguments);
1670         } else {
1671             var self = this;
1672             var pop = new openerp.base.form.SelectCreatePopup(null, self.o2m.view.session);
1673             pop.select_element(self.o2m.field.relation,{
1674                 initial_view: "form",
1675                 alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
1676                 auto_create: false,
1677                 parent_view: self.o2m.view
1678             }, self.o2m.build_domain(), self.o2m.build_context());
1679             pop.on_create.add(function(data) {
1680                 self.o2m.dataset.create(data, function(r) {
1681                     self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
1682                     self.o2m.dataset.on_change();
1683                     pop.stop();
1684                     self.o2m.reload_current_view();
1685                 });
1686             });
1687         }
1688     }
1689 });
1690
1691 openerp.base.form.FieldMany2Many = openerp.base.form.Field.extend({
1692     multi_selection: false,
1693     init: function(view, node) {
1694         this._super(view, node);
1695         this.template = "FieldMany2Many";
1696         this.list_id = _.uniqueId("many2many");
1697         this.is_started = $.Deferred();
1698     },
1699     start: function() {
1700         this._super.apply(this, arguments);
1701
1702         var self = this;
1703
1704         this.dataset = new openerp.base.form.Many2ManyDataSet(
1705                 this.session, this.field.relation);
1706         this.dataset.m2m = this;
1707         this.dataset.on_unlink.add_last(function(ids) {
1708             self.on_ui_change();
1709         });
1710
1711         this.list_view = new openerp.base.form.Many2ManyListView(
1712                 null, this.view.session, this.list_id, this.dataset, false, {
1713                     'addable': 'Add',
1714                     'selectable': self.multi_selection
1715             });
1716         this.list_view.m2m_field = this;
1717         this.list_view.on_loaded.add_last(function() {
1718             self.is_started.resolve();
1719         });
1720         setTimeout(function () {
1721             self.list_view.start();
1722         }, 0);
1723     },
1724     set_value: function(value) {
1725         value = value || [];
1726         if (value.length >= 1 && value[0] instanceof Array) {
1727             value = value[0][2];
1728         }
1729         this._super(value);
1730         this.dataset.set_ids(value);
1731         var self = this;
1732         $.when(this.is_started).then(function() {
1733             self.list_view.reload_content();
1734         });
1735     },
1736     get_value: function() {
1737         return [commands.replace_with(this.dataset.ids)];
1738     },
1739     set_value_from_ui: function() {},
1740     validate: function() {
1741         this.invalid = false;
1742         // TODO niv
1743     }
1744 });
1745
1746 openerp.base.form.Many2ManyDataSet = openerp.base.DataSetStatic.extend({
1747     get_context: function() {
1748         this.context = this.m2m.build_context();
1749         return this.context;
1750     }
1751 });
1752
1753 openerp.base.form.Many2ManyListView = openerp.base.ListView.extend({
1754     do_add_record: function () {
1755         var pop = new openerp.base.form.SelectCreatePopup(
1756                 null, this.m2m_field.view.session);
1757         pop.select_element(this.model, {},
1758             new openerp.base.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
1759             this.m2m_field.build_context());
1760         var self = this;
1761         pop.on_select_elements.add(function(element_ids) {
1762             _.each(element_ids, function(element_id) {
1763                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
1764                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
1765                     self.m2m_field.on_ui_change();
1766                     self.reload_content();
1767                 }
1768             });
1769             pop.stop();
1770         });
1771     },
1772     do_activate_record: function(index, id) {
1773         this.m2m_field.view.session.action_manager.do_action({
1774             "res_model": this.dataset.model,
1775             "views": [[false,"form"]],
1776             "res_id": id,
1777             "type": "ir.actions.act_window",
1778             "view_type": "form",
1779             "view_mode": "form",
1780             "target": "new",
1781             "context": this.m2m_field.build_context()
1782         });
1783     }
1784 });
1785
1786 openerp.base.form.SelectCreatePopup = openerp.base.BaseWidget.extend({
1787     identifier_prefix: "selectcreatepopup",
1788     template: "SelectCreatePopup",
1789     /**
1790      * options:
1791      * - initial_ids
1792      * - initial_view: form or search (default search)
1793      * - disable_multiple_selection
1794      * - alternative_form_view
1795      * - auto_create (default true)
1796      * - parent_view
1797      */
1798     select_element: function(model, options, domain, context) {
1799         this.model = model;
1800         this.domain = domain || [];
1801         this.context = context || {};
1802         this.options = _.defaults(options || {}, {"initial_view": "search", "auto_create": true});
1803         this.initial_ids = this.options.initial_ids;
1804         jQuery(this.render()).dialog({title: '',
1805                     modal: true,
1806                     minWidth: 800});
1807         this.start();
1808     },
1809     start: function() {
1810         this._super();
1811         this.dataset = new openerp.base.ReadOnlyDataSetSearch(this.session, this.model,
1812             this.context);
1813         this.dataset.parent_view = this.options.parent_view;
1814         if (this.options.initial_view == "search") {
1815             this.setup_search_view();
1816         } else { // "form"
1817             this.new_object();
1818         }
1819     },
1820     setup_search_view: function() {
1821         var self = this;
1822         if (this.searchview) {
1823             this.searchview.stop();
1824         }
1825         this.searchview = new openerp.base.SearchView(null, this.session,
1826                 this.element_id + "_search", this.dataset, false, {
1827                     "selectable": !this.options.disable_multiple_selection,
1828                     "deletable": false
1829                 });
1830         this.searchview.on_search.add(function(domains, contexts, groupbys) {
1831             if (self.initial_ids) {
1832                 self.view_list.do_search.call(self, domains.concat([[["id", "in", self.initial_ids]], self.domain]),
1833                     contexts, groupbys);
1834                 self.initial_ids = undefined;
1835             } else {
1836                 self.view_list.do_search.call(self, domains.concat([self.domain]), contexts, groupbys);
1837             }
1838         });
1839         this.searchview.on_loaded.add_last(function () {
1840             var $buttons = self.searchview.$element.find(".oe_search-view-buttons");
1841             $buttons.append(QWeb.render("SelectCreatePopup.search.buttons"));
1842             var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
1843             $cbutton.click(function() {
1844                 self.stop();
1845             });
1846             var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
1847             if(self.options.disable_multiple_selection) {
1848                 $sbutton.hide();
1849             }
1850             $sbutton.click(function() {
1851                 self.on_select_elements(self.selected_ids);
1852             });
1853             self.view_list = new openerp.base.form.SelectCreateListView( null, self.session,
1854                     self.element_id + "_view_list", self.dataset, false,
1855                     {'deletable': false});
1856             self.view_list.popup = self;
1857             self.view_list.do_show();
1858             self.view_list.start().then(function() {
1859                 self.searchview.do_search();
1860             });
1861         });
1862         this.searchview.start();
1863     },
1864     on_create: function(data) {
1865         if (!this.options.auto_create)
1866             return;
1867         var self = this;
1868         var wdataset = new openerp.base.DataSetSearch(this.session, this.model, this.context, this.domain);
1869         wdataset = this.options.parent_view;
1870         wdataset.create(data, function(r) {
1871             self.on_select_elements([r.result]);
1872         });
1873     },
1874     on_select_elements: function(element_ids) {
1875     },
1876     on_click_element: function(ids) {
1877         this.selected_ids = ids || [];
1878         if(this.selected_ids.length > 0) {
1879             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
1880         } else {
1881             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
1882         }
1883     },
1884     new_object: function() {
1885         var self = this;
1886         if (this.searchview) {
1887             this.searchview.hide();
1888         }
1889         if (this.view_list) {
1890             this.view_list.$element.hide();
1891         }
1892         this.dataset.index = null;
1893         this.view_form = new openerp.base.FormView(null, this.session,
1894                 this.element_id + "_view_form", this.dataset, false);
1895         if (this.options.alternative_form_view) {
1896             this.view_form.set_embedded_view(this.options.alternative_form_view);
1897         }
1898         this.view_form.start();
1899         this.view_form.on_loaded.add_last(function() {
1900             var $buttons = self.view_form.$element.find(".oe_form_buttons");
1901             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons"));
1902             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
1903             $nbutton.click(function() {
1904                 self.view_form.do_save();
1905             });
1906             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
1907             $cbutton.click(function() {
1908                 self.stop();
1909             });
1910         });
1911         this.dataset.on_create.add(this.on_create);
1912         this.view_form.do_show();
1913     }
1914 });
1915
1916 openerp.base.form.SelectCreateListView = openerp.base.ListView.extend({
1917     do_add_record: function () {
1918         this.popup.new_object();
1919     },
1920     select_record: function(index) {
1921         this.popup.on_select_elements([this.dataset.ids[index]]);
1922     },
1923     do_select: function(ids, records) {
1924         this._super(ids, records);
1925         this.popup.on_click_element(ids);
1926     }
1927 });
1928
1929 openerp.base.form.FieldReference = openerp.base.form.Field.extend({
1930     init: function(view, node) {
1931         this._super(view, node);
1932         this.template = "FieldReference";
1933     }
1934 });
1935
1936 openerp.base.form.FieldBinary = openerp.base.form.Field.extend({
1937     init: function(view, node) {
1938         this._super(view, node);
1939         this.iframe = this.element_id + '_iframe';
1940         this.binary_value = false;
1941     },
1942     start: function() {
1943         this._super.apply(this, arguments);
1944         this.$element.find('input.oe-binary-file').change(this.on_file_change);
1945         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
1946         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
1947     },
1948     set_value_from_ui: function() {
1949     },
1950     human_filesize : function(size) {
1951         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
1952         var i = 0;
1953         while (size >= 1024) {
1954             size /= 1024;
1955             ++i;
1956         }
1957         return size.toFixed(2) + ' ' + units[i];
1958     },
1959     on_file_change: function(e) {
1960         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
1961         // http://www.html5rocks.com/tutorials/file/dndfiles/
1962         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
1963         window[this.iframe] = this.on_file_uploaded;
1964         if ($(e.target).val() != '') {
1965             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
1966             this.$element.find('form.oe-binary-form').submit();
1967             this.toggle_progress();
1968         }
1969     },
1970     toggle_progress: function() {
1971         this.$element.find('.oe-binary-progress, .oe-binary').toggle();
1972     },
1973     on_file_uploaded: function(size, name, content_type, file_base64) {
1974         delete(window[this.iframe]);
1975         if (size === false) {
1976             this.notification.warn("File Upload", "There was a problem while uploading your file");
1977             // TODO: use openerp web exception handler
1978             console.log("Error while uploading file : ", name);
1979         } else {
1980             this.on_file_uploaded_and_valid.apply(this, arguments);
1981             this.on_ui_change();
1982         }
1983         this.toggle_progress();
1984     },
1985     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
1986     },
1987     on_save_as: function() {
1988         if (!this.view.datarecord.id) {
1989             this.notification.warn("Can't save file", "The record has not yet been saved");
1990         } else {
1991             var url = '/base/binary/saveas?session_id=' + this.session.session_id + '&model=' +
1992                 this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name +
1993                 '&fieldname=' + (this.node.attrs.filename || '') + '&t=' + (new Date().getTime())
1994             window.open(url);
1995         }
1996     },
1997     on_clear: function() {
1998         if (this.value !== false) {
1999             this.value = false;
2000             this.binary_value = false;
2001             this.on_ui_change();
2002         }
2003         return false;
2004     }
2005 });
2006
2007 openerp.base.form.FieldBinaryFile = openerp.base.form.FieldBinary.extend({
2008     init: function(view, node) {
2009         this._super(view, node);
2010         this.template = "FieldBinaryFile";
2011     },
2012     set_value: function(value) {
2013         this._super.apply(this, arguments);
2014         var show_value = (value != null && value !== false) ? value : '';
2015         this.$element.find('input').eq(0).val(show_value);
2016     },
2017     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2018         this.value = file_base64;
2019         this.binary_value = true;
2020         var show_value = this.human_filesize(size);
2021         this.$element.find('input').eq(0).val(show_value);
2022         this.set_filename(name);
2023     },
2024     set_filename: function(value) {
2025         var filename = this.node.attrs.filename;
2026         if (this.view.fields[filename]) {
2027             this.view.fields[filename].set_value(value);
2028             this.view.fields[filename].on_ui_change();
2029         }
2030     },
2031     on_clear: function() {
2032         this._super.apply(this, arguments);
2033         this.$element.find('input').eq(0).val('');
2034         this.set_filename('');
2035     }
2036 });
2037
2038 openerp.base.form.FieldBinaryImage = openerp.base.form.FieldBinary.extend({
2039     init: function(view, node) {
2040         this._super(view, node);
2041         this.template = "FieldBinaryImage";
2042     },
2043     start: function() {
2044         this._super.apply(this, arguments);
2045         this.$image = this.$element.find('img.oe-binary-image');
2046     },
2047     set_image_maxwidth: function() {
2048         this.$image.css('max-width', this.$element.width());
2049     },
2050     on_file_change: function() {
2051         this.set_image_maxwidth();
2052         this._super.apply(this, arguments);
2053     },
2054     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
2055         this.value = file_base64;
2056         this.binary_value = true;
2057         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
2058     },
2059     on_clear: function() {
2060         this._super.apply(this, arguments);
2061         this.$image.attr('src', '/base/static/src/img/placeholder.png');
2062     },
2063     set_value: function(value) {
2064         this._super.apply(this, arguments);
2065         this.set_image_maxwidth();
2066         var url = '/base/binary/image?session_id=' + this.session.session_id + '&model=' +
2067             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime())
2068         this.$image.attr('src', url);
2069     }
2070 });
2071
2072 /**
2073  * Registry of form widgets, called by :js:`openerp.base.FormView`
2074  */
2075 openerp.base.form.widgets = new openerp.base.Registry({
2076     'frame' : 'openerp.base.form.WidgetFrame',
2077     'group' : 'openerp.base.form.WidgetFrame',
2078     'notebook' : 'openerp.base.form.WidgetNotebook',
2079     'separator' : 'openerp.base.form.WidgetSeparator',
2080     'label' : 'openerp.base.form.WidgetLabel',
2081     'button' : 'openerp.base.form.WidgetButton',
2082     'char' : 'openerp.base.form.FieldChar',
2083     'email' : 'openerp.base.form.FieldEmail',
2084     'url' : 'openerp.base.form.FieldUrl',
2085     'text' : 'openerp.base.form.FieldText',
2086     'text_wiki' : 'openerp.base.form.FieldText',
2087     'date' : 'openerp.base.form.FieldDate',
2088     'datetime' : 'openerp.base.form.FieldDatetime',
2089     'selection' : 'openerp.base.form.FieldSelection',
2090     'many2one' : 'openerp.base.form.FieldMany2One',
2091     'many2many' : 'openerp.base.form.FieldMany2Many',
2092     'one2many' : 'openerp.base.form.FieldOne2Many',
2093     'one2many_list' : 'openerp.base.form.FieldOne2Many',
2094     'reference' : 'openerp.base.form.FieldReference',
2095     'boolean' : 'openerp.base.form.FieldBoolean',
2096     'float' : 'openerp.base.form.FieldFloat',
2097     'integer': 'openerp.base.form.FieldInteger',
2098     'progressbar': 'openerp.base.form.FieldProgressBar',
2099     'float_time': 'openerp.base.form.FieldFloatTime',
2100     'image': 'openerp.base.form.FieldBinaryImage',
2101     'binary': 'openerp.base.form.FieldBinaryFile'
2102 });
2103
2104 };
2105
2106 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: