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