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