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