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