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