Aleksander Machniak
2016-02-24 b0a8e3693090bd96fc31c4c5f42b77f8fddf9b90
commit | author | age
b34d67 1 /**
TB 2  * Roundcube editor js library
3  *
4  * This file is part of the Roundcube Webmail client
5  *
6  * @licstart  The following is the entire license notice for the
7  * JavaScript code in this file.
8  *
9  * Copyright (c) 2006-2014, The Roundcube Dev Team
10  *
11  * The JavaScript code in this page is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU
13  * General Public License (GNU GPL) as published by the Free Software
14  * Foundation, either version 3 of the License, or (at your option)
15  * any later version.  The code is distributed WITHOUT ANY WARRANTY;
16  * without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
18  *
19  * As additional permission under GNU GPL version 3 section 7, you
20  * may distribute non-source (e.g., minimized or compacted) forms of
21  * that code without the copy of the GNU GPL normally required by
22  * section 4, provided you include this license notice and a URL
23  * through which recipients can access the Corresponding Source.
24  *
25  * @licend  The above is the entire license notice
26  * for the JavaScript code in this file.
27  *
28  * @author Eric Stadtherr <estadtherr@gmail.com>
646b64 29  * @author Aleksander Machniak <alec@alec.pl>
b34d67 30  */
a0109c 31
646b64 32 /**
AM 33  * Roundcube Text Editor Widget class
34  * @constructor
35  */
36 function rcube_text_editor(config, id)
4ca10b 37 {
646b64 38   var ref = this,
681ba6 39     abs_url = location.href.replace(/[?#].*$/, '').replace(/\/$/, ''),
646b64 40     conf = {
AM 41       selector: '#' + ($('#' + id).is('.mce_editor') ? id : 'fake-editor-id'),
eb721e 42       cache_suffix: 's=4020700',
6fa5b4 43       theme: 'modern',
66df08 44       language: config.lang,
681ba6 45       content_css: rcmail.assets_path('program/js/tinymce/roundcube/content.css'),
6fa5b4 46       menubar: false,
AM 47       statusbar: false,
ccb417 48       toolbar_items_size: 'small',
2d889e 49       extended_valid_elements: 'font[face|size|color|style],span[id|class|align|style]',
e0a5ce 50       relative_urls: false,
A 51       remove_script_host: false,
2d889e 52       convert_urls: false, // #1486944
89d6ce 53       image_description: false,
AM 54       paste_webkit_style: "color font-size font-family",
815804 55       paste_data_images: true,
VB 56       browser_spellcheck: true
2d889e 57     };
A 58
646b64 59   // register spellchecker for plain text editor
AM 60   this.spellcheck_observer = function() {};
61   if (config.spellchecker) {
62     this.spellchecker = config.spellchecker;
63     if (config.spellcheck_observer) {
64       this.spellchecker.spelling_state_observer = this.spellcheck_observer = config.spellcheck_observer;
65     }
66   }
67
b0bb38 68   // secure spellchecker requests with Roundcube token
AM 69   // Note: must be registered only once (#1490311)
70   if (!tinymce.registered_request_token) {
71     tinymce.registered_request_token = true;
72     tinymce.util.XHR.on('beforeSend', function(e) {
73       e.xhr.setRequestHeader('X-Roundcube-Request', rcmail.env.request_token);
0bde1c 74       // Fix missing lang parameter on addToDictionary request (#1490634)
AM 75       if (e.settings && e.settings.data && /^method=addToDictionary/.test(e.settings.data) && !/&lang=/.test(e.settings.data))
76         e.settings.data += '&lang=' + ref.editor.plugins.spellchecker.getLanguage();
b0bb38 77     });
AM 78   }
79
646b64 80   // minimal editor
AM 81   if (config.mode == 'identity') {
2d889e 82     $.extend(conf, {
3cc1af 83       plugins: 'autolink charmap code colorpicker hr image link paste tabfocus textcolor',
6fa5b4 84       toolbar: 'bold italic underline alignleft aligncenter alignright alignjustify'
3cc1af 85         + ' | outdent indent charmap hr link unlink image code forecolor'
AM 86         + ' | fontselect fontsizeselect',
87       file_browser_callback: function(name, url, type, win) { ref.file_browser_callback(name, url, type); },
88       file_browser_callback_types: 'image'
b8ae50 89     });
646b64 90   }
AM 91   // full-featured editor
92   else {
2d889e 93     $.extend(conf, {
2aa9ee 94       plugins: 'autolink charmap code colorpicker directionality link image media nonbreaking'
a63f14 95         + ' paste table tabfocus textcolor searchreplace spellchecker',
6fa5b4 96       toolbar: 'bold italic underline | alignleft aligncenter alignright alignjustify'
89d6ce 97         + ' | bullist numlist outdent indent ltr rtl blockquote | forecolor backcolor | fontselect fontsizeselect'
2aa9ee 98         + ' | link unlink table | $extra charmap image media | code searchreplace undo redo',
681ba6 99       spellchecker_rpc_url: abs_url + '/?_task=utils&_action=spell_html&_remote=1',
4d0238 100       spellchecker_language: rcmail.env.spell_lang,
2d889e 101       accessibility_focus: false,
646b64 102       file_browser_callback: function(name, url, type, win) { ref.file_browser_callback(name, url, type); },
b21f8b 103       // @todo: support more than image (types: file, image, media)
c5bfe6 104       file_browser_callback_types: 'image media'
b8ae50 105     });
4be86f 106   }
A 107
2aa9ee 108   // add TinyMCE plugins/buttons from Roundcube plugin
AM 109   $.each(config.extra_plugins || [], function() {
110     if (conf.plugins.indexOf(this) < 0)
111       conf.plugins = conf.plugins + ' ' + this;
112   });
113   $.each(config.extra_buttons || [], function() {
114     if (conf.toolbar.indexOf(this) < 0)
115       conf.toolbar = conf.toolbar.replace('$extra', '$extra ' + this);
116   });
117
a63f14 118   // disable TinyMCE plugins/buttons from Roundcube plugin
AM 119   $.each(config.disabled_plugins || [], function() {
120     conf.plugins = conf.plugins.replace(this, '');
121   });
87d6d2 122   $.each(config.disabled_buttons || [], function() {
a63f14 123     conf.toolbar = conf.toolbar.replace(this, '');
AM 124   });
2aa9ee 125
AM 126   conf.toolbar = conf.toolbar.replace('$extra', '').replace(/\|\s+\|/g, '|');
a63f14 127
2d889e 128   // support external configuration settings e.g. from skin
A 129   if (window.rcmail_editor_settings)
130     $.extend(conf, window.rcmail_editor_settings);
131
646b64 132   conf.setup = function(ed) {
AM 133     ed.on('init', function(ed) { ref.init_callback(ed); });
134     // add handler for spellcheck button state update
135     ed.on('SpellcheckStart SpellcheckEnd', function(args) {
136       ref.spellcheck_active = args.type == 'spellcheckstart';
137       ref.spellcheck_observer();
138     });
139     ed.on('keypress', function() {
140       rcmail.compose_type_activity++;
a8f4d8 141     });
646b64 142   };
AM 143
144   // textarea identifier
145   this.id = id;
146   // reference to active editor (if in HTML mode)
147   this.editor = null;
148
6fa5b4 149   tinymce.init(conf);
b8ae50 150
646b64 151   // react to real individual tinyMCE editor init
AM 152   this.init_callback = function(event)
153   {
154     this.editor = event.target;
c288f9 155
646b64 156     if (rcmail.env.action != 'compose') {
AM 157       return;
43fb35 158     }
c288f9 159
a172f3 160     var area = $('#' + this.id),
AM 161       height = $('div.mce-toolbar-grp:first', area.parent()).height();
162
163     // the editor might be still not fully loaded, making the editing area
164     // inaccessible, wait and try again (#1490310)
165     if (height > 200 || height > area.height()) {
166       return setTimeout(function () { ref.init_callback(event); }, 300);
167     }
168
646b64 169     var css = {},
AM 170       elem = rcube_find_object('_from'),
171       fe = rcmail.env.compose_focus_elem;
665cc5 172
646b64 173     if (rcmail.env.default_font)
AM 174       css['font-family'] = rcmail.env.default_font;
175
176     if (rcmail.env.default_font_size)
177       css['font-size'] = rcmail.env.default_font_size;
178
179     if (css['font-family'] || css['font-size'])
180       $(this.editor.getBody()).css(css);
181
182     if (elem && elem.type == 'select-one') {
183       // insert signature (only for the first time)
184       if (!rcmail.env.identities_initialized)
185         rcmail.change_identity(elem);
186
187       // Focus previously focused element
188       if (fe && fe.id != this.id) {
a172f3 189         window.focus(); // for WebKit (#1486674)
AM 190         fe.focus();
191         rcmail.env.compose_focus_elem = null;
646b64 192       }
AM 193     }
194
a172f3 195     // set tabIndex and set focus to element that was focused before
AM 196     ref.tabindex(fe && fe.id == ref.id);
197     // Trigger resize (needed for proper editor resizing in some browsers)
198     $(window).resize();
646b64 199   };
AM 200
201   // set tabIndex on tinymce editor
202   this.tabindex = function(focus)
203   {
204     if (rcmail.env.task == 'mail' && this.editor) {
205       var textarea = this.editor.getElement(),
aa1ddf 206         body = this.editor.getBody(),
646b64 207         node = this.editor.getContentAreaContainer().childNodes[0];
89d6ce 208
4cdc70 209       if (textarea && node)
A 210         node.tabIndex = textarea.tabIndex;
23c00e 211
TB 212       // find :prev and :next elements to get focus when tabbing away
213       if (textarea.tabIndex > 0) {
214         var x = null,
215           tabfocus_elements = [':prev',':next'],
216           el = tinymce.DOM.select('*[tabindex='+textarea.tabIndex+']:not(iframe)');
aa1ddf 217
AM 218         tinymce.each(el, function(e, i) { if (e.id == ref.id) { x = i; return false; } });
23c00e 219         if (x !== null) {
TB 220           if (el[x-1] && el[x-1].id) {
221             tabfocus_elements[0] = el[x-1].id;
222           }
223           if (el[x+1] && el[x+1].id) {
224             tabfocus_elements[1] = el[x+1].id;
225           }
aa1ddf 226           this.editor.settings.tabfocus_elements = tabfocus_elements.join(',');
23c00e 227         }
TB 228       }
aa1ddf 229
AM 230       // ContentEditable reset fixes invisible cursor issue in Firefox < 25
231       if (bw.mz && bw.vendver < 25)
232         $(body).prop('contenteditable', false).prop('contenteditable', true);
233
234       if (focus)
235         body.focus();
4cdc70 236     }
646b64 237   };
b8ae50 238
646b64 239   // switch html/plain mode
7d3be1 240   this.toggle = function(ishtml, noconvert)
646b64 241   {
AM 242     var curr, content, result,
243       // these non-printable chars are not removed on text2html and html2text
244       // we can use them as temp signature replacement
245       sig_mark = "\u0002\u0003",
246       input = $('#' + this.id),
247       signature = rcmail.env.identity ? rcmail.env.signatures[rcmail.env.identity] : null,
248       is_sig = signature && signature.text && signature.text.length > 1;
5821ff 249
646b64 250     // apply spellcheck changes if spell checker is active
AM 251     this.spellcheck_stop();
8f142e 252
646b64 253     if (ishtml) {
AM 254       content = input.val();
8f142e 255
646b64 256       // replace current text signature with temp mark
b0c902 257       if (is_sig) {
AM 258         content = content.replace(/\r\n/, "\n");
259         content = content.replace(signature.text.replace(/\r\n/, "\n"), sig_mark);
260       }
b21f8b 261
7d3be1 262       var init_editor = function(data) {
646b64 263         // replace signature mark with html version of the signature
AM 264         if (is_sig)
265           data = data.replace(sig_mark, '<div id="_rc_sig">' + signature.html + '</div>');
b21f8b 266
646b64 267         input.val(data);
AM 268         tinymce.execCommand('mceAddEditor', false, ref.id);
269
a172f3 270         if (ref.editor) {
AM 271           var body = $(ref.editor.getBody());
272           // #1486593
273           ref.tabindex(true);
274           // put cursor on start of the compose body
275           ref.editor.selection.setCursorLocation(body.children().first().get(0));
276         }
7d3be1 277       };
TB 278
279       // convert to html
280       if (!noconvert) {
281         result = rcmail.plain2html(content, init_editor);
282       }
283       else {
284         init_editor(content);
285         result = true;
286       }
8f142e 287     }
646b64 288     else if (this.editor) {
AM 289       if (is_sig) {
290         // get current version of signature, we'll need it in
291         // case of html2text conversion abort
292         if (curr = this.editor.dom.get('_rc_sig'))
293           curr = curr.innerHTML;
8f142e 294
646b64 295         // replace current signature with some non-printable characters
AM 296         // we use non-printable characters, because this replacement
297         // is visible to the user
298         // doing this after getContent() would be hard
299         this.editor.dom.setHTML('_rc_sig', sig_mark);
b21f8b 300       }
AM 301
646b64 302       // get html content
AM 303       content = this.editor.getContent();
b21f8b 304
7d3be1 305       var init_plaintext = function(data) {
646b64 306         tinymce.execCommand('mceRemoveEditor', false, ref.id);
AM 307         ref.editor = null;
b21f8b 308
646b64 309         // replace signture mark with text version of the signature
AM 310         if (is_sig)
311           data = data.replace(sig_mark, "\n" + signature.text);
b21f8b 312
646b64 313         input.val(data).focus();
aa1ddf 314         rcmail.set_caret_pos(input.get(0), 0);
7d3be1 315       };
TB 316
317       // convert html to text
318       if (!noconvert) {
319         result = rcmail.html2plain(content, init_plaintext);
320       }
321       else {
322         init_plaintext(input.val());
323         result = true;
324       }
b21f8b 325
646b64 326       // bring back current signature
AM 327       if (!result && curr)
328         this.editor.dom.setHTML('_rc_sig', curr);
329     }
b21f8b 330
646b64 331     return result;
AM 332   };
b21f8b 333
646b64 334   // start spellchecker
AM 335   this.spellcheck_start = function()
336   {
337     if (this.editor) {
338       tinymce.execCommand('mceSpellCheck', true);
339       this.spellcheck_observer();
340     }
341     else if (this.spellchecker && this.spellchecker.spellCheck) {
342       this.spellchecker.spellCheck();
343     }
344   };
b21f8b 345
646b64 346   // stop spellchecker
AM 347   this.spellcheck_stop = function()
348   {
349     var ed = this.editor;
b21f8b 350
646b64 351     if (ed) {
a8f4d8 352       if (ed.plugins && ed.plugins.spellchecker && this.spellcheck_active) {
AM 353         ed.execCommand('mceSpellCheck', false);
646b64 354         this.spellcheck_observer();
a8f4d8 355       }
646b64 356     }
AM 357     else if (ed = this.spellchecker) {
358       if (ed.state && ed.state != 'ready' && ed.state != 'no_error_found')
359         $(ed.spell_span).trigger('click');
360     }
361   };
b21f8b 362
646b64 363   // spellchecker state
AM 364   this.spellcheck_state = function()
365   {
366     var ed;
b21f8b 367
646b64 368     if (this.editor)
AM 369       return this.spellcheck_active;
370     else if ((ed = this.spellchecker) && ed.state)
371       return ed.state != 'ready' && ed.state != 'no_error_found';
372   };
b21f8b 373
a8f4d8 374   // resume spellchecking, highlight provided mispellings without a new ajax request
646b64 375   this.spellcheck_resume = function(data)
AM 376   {
377     var ed = this.editor;
378
379     if (ed) {
a8f4d8 380       ed.plugins.spellchecker.markErrors(data);
646b64 381     }
AM 382     else if (ed = this.spellchecker) {
383       ed.prepare(false, true);
384       ed.processData(data);
385     }
386   };
387
388   // get selected (spellcheker) language
389   this.get_language = function()
390   {
391     if (this.editor) {
392       return this.editor.settings.spellchecker_language || rcmail.env.spell_lang;
393     }
394     else if (this.spellchecker) {
395       return GOOGIE_CUR_LANG;
396     }
397   };
398
399   // set language for spellchecking
400   this.set_language = function(lang)
401   {
402     var ed = this.editor;
403
404     if (ed) {
405       ed.settings.spellchecker_language = lang;
406     }
407     if (ed = this.spellchecker) {
408       ed.setCurrentLanguage(lang);
409     }
410   };
411
412   // replace selection with text snippet
413   this.replace = function(text)
414   {
415     var ed = this.editor;
416
417     // insert into tinymce editor
418     if (ed) {
419       ed.getWin().focus(); // correct focus in IE & Chrome
420       ed.selection.setContent(rcmail.quote_html(text).replace(/\r?\n/g, '<br/>'), { format:'text' });
421     }
422     // replace selection in compose textarea
423     else if (ed = rcube_find_object(this.id)) {
424       var selection = $(ed).is(':focus') ? rcmail.get_input_selection(ed) : { start:0, end:0 },
425         inp_value = ed.value;
426         pre = inp_value.substring(0, selection.start),
427         end = inp_value.substring(selection.end, inp_value.length);
428
429       // insert response text
430       ed.value = pre + text + end;
431
432       // set caret after inserted text
433       rcmail.set_caret_pos(ed, selection.start + text.length);
434       ed.focus();
435     }
436   };
437
438   // get selected text (if no selection returns all text) from the editor
45bfde 439   this.get_content = function(args)
646b64 440   {
45bfde 441     var sigstart, ed = this.editor, text = '', strip = false,
AM 442       defaults = {refresh: true, selection: false, nosig: false, format: 'html'};
646b64 443
45bfde 444     args = $.extend(defaults, args);
AM 445
446     // apply spellcheck changes if spell checker is active
447     if (args.refresh) {
448       this.spellcheck_stop();
449     }
646b64 450
AM 451     // get selected text from tinymce editor
452     if (ed) {
453       ed.getWin().focus(); // correct focus in IE & Chrome
45bfde 454       if (args.selection)
AM 455         text = ed.selection.getContent({format: args.format});
646b64 456
AM 457       if (!text) {
45bfde 458         text = ed.getContent({format: args.format});
AM 459         // @todo: strip signature in html mode
460         strip = args.format == 'text';
646b64 461       }
AM 462     }
463     // get selected text from compose textarea
464     else if (ed = rcube_find_object(this.id)) {
45bfde 465       if (args.selection && $(ed).is(':focus')) {
646b64 466         text = rcmail.get_input_selection(ed).text;
AM 467       }
468
469       if (!text) {
470         text = ed.value;
471         strip = true;
472       }
473     }
474
475     // strip off signature
45bfde 476     // @todo: make this optional
AM 477     if (strip && args.nosig) {
646b64 478       sigstart = text.indexOf('-- \n');
AM 479       if (sigstart > 0) {
480         text = text.substring(0, sigstart);
481       }
482     }
483
484     return text;
485   };
486
487   // change user signature text
488   this.change_signature = function(id, show_sig)
489   {
aa1ddf 490     var position_element, cursor_pos, p = -1,
646b64 491       input_message = $('#' + this.id),
AM 492       message = input_message.val(),
493       sig = rcmail.env.identity;
494
495     if (!this.editor) { // plain text mode
496       // remove the 'old' signature
497       if (show_sig && sig && rcmail.env.signatures && rcmail.env.signatures[sig]) {
498         sig = rcmail.env.signatures[sig].text;
499         sig = sig.replace(/\r\n/g, '\n');
500
501         p = rcmail.env.top_posting ? message.indexOf(sig) : message.lastIndexOf(sig);
502         if (p >= 0)
503           message = message.substring(0, p) + message.substring(p+sig.length, message.length);
504       }
aa1ddf 505
646b64 506       // add the new signature string
AM 507       if (show_sig && rcmail.env.signatures && rcmail.env.signatures[id]) {
508         sig = rcmail.env.signatures[id].text;
509         sig = sig.replace(/\r\n/g, '\n');
510
09225a 511         // in place of removed signature
AM 512         if (p >= 0) {
513           message = message.substring(0, p) + sig + message.substring(p, message.length);
514           cursor_pos = p - 1;
515         }
b0a8e3 516         // empty message or new-message mode
AM 517         else if (!message || !rcmail.env.compose_mode) {
518           cursor_pos = message.length;
519           message += '\n\n' + sig;
09225a 520         }
AM 521         else if (rcmail.env.top_posting && !rcmail.env.sig_below) {
522           // at cursor position
523           if (pos = rcmail.get_caret_pos(input_message.get(0))) {
646b64 524             message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
AM 525             cursor_pos = pos;
526           }
09225a 527           // on top
AM 528           else {
646b64 529             message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
09225a 530             cursor_pos = 0;
646b64 531           }
AM 532         }
533         else {
534           message = message.replace(/[\r\n]+$/, '');
09225a 535           cursor_pos = !rcmail.env.top_posting && message.length ? message.length + 1 : 0;
646b64 536           message += '\n\n' + sig;
AM 537         }
538       }
09225a 539       else {
646b64 540         cursor_pos = rcmail.env.top_posting ? 0 : message.length;
09225a 541       }
646b64 542
AM 543       input_message.val(message);
544
545       // move cursor before the signature
546       rcmail.set_caret_pos(input_message.get(0), cursor_pos);
547     }
548     else if (show_sig && rcmail.env.signatures) {  // html
549       var sigElem = this.editor.dom.get('_rc_sig');
550
551       // Append the signature as a div within the body
552       if (!sigElem) {
bcd379 553         var body = this.editor.getBody();
646b64 554
bcd379 555         sigElem = $('<div id="_rc_sig"></div>').get(0);
646b64 556
bcd379 557         // insert at start or at cursor position in top-posting mode
b0a8e3 558         // (but not if the content is empty and not in new-message mode)
AM 559         if (rcmail.env.top_posting && !rcmail.env.sig_below
560           && rcmail.env.compose_mode && (body.childNodes.length > 1 || $(body).text())
561         ) {
646b64 562           this.editor.getWin().focus(); // correct focus in IE & Chrome
AM 563
564           var node = this.editor.selection.getNode();
09225a 565
bcd379 566           $(sigElem).insertBefore(node.nodeName == 'BODY' ? body.firstChild : node.nextSibling);
AM 567           $('<p>').append($('<br>')).insertBefore(sigElem);
646b64 568         }
AM 569         else {
570           body.appendChild(sigElem);
b0a8e3 571           position_element = rcmail.env.top_posting && rcmail.env.compose_mode ? body.firstChild : $(sigElem).prev();
646b64 572         }
b21f8b 573       }
646b64 574
8449e9 575       sigElem.innerHTML = rcmail.env.signatures[id] ? rcmail.env.signatures[id].html : '';
646b64 576     }
aa1ddf 577     else if (!rcmail.env.top_posting) {
AM 578       position_element = $(this.editor.getBody()).children().last();
579     }
580
581     // put cursor before signature and scroll the window
582     if (this.editor && position_element && position_element.length) {
583       this.editor.selection.setCursorLocation(position_element.get(0));
584       this.editor.getWin().scroll(0, position_element.offset().top);
585     }
646b64 586   };
AM 587
588   // trigger content save
589   this.save = function()
590   {
591     if (this.editor) {
592       this.editor.save();
593     }
594   };
595
596   // focus the editing area
597   this.focus = function()
598   {
599     (this.editor || rcube_find_object(this.id)).focus();
600   };
601
602   // image selector
603   this.file_browser_callback = function(field_name, url, type)
604   {
5b2311 605     var i, elem, cancel, dialog, fn, list = [];
646b64 606
AM 607     // open image selector dialog
608     dialog = this.editor.windowManager.open({
8f8bea 609       title: rcmail.get_label('select' + type),
646b64 610       width: 500,
AM 611       height: 300,
612       html: '<div id="image-selector-list"><ul></ul></div>'
5b2311 613         + '<div id="image-selector-form"><div id="image-upload-button" class="mce-widget mce-btn" role="button" tabindex="0"></div></div>',
646b64 614       buttons: [{text: 'Cancel', onclick: function() { ref.file_browser_close(); }}]
AM 615     });
616
617     rcmail.env.file_browser_field = field_name;
618     rcmail.env.file_browser_type = type;
619
620     // fill images list with available images
621     for (i in rcmail.env.attachments) {
622       if (elem = ref.file_browser_entry(i, rcmail.env.attachments[i])) {
623         list.push(elem);
624       }
625     }
626
627     if (list.length) {
5b2311 628       $('#image-selector-list > ul').append(list).find('li:first').focus();
646b64 629     }
AM 630
631     // add hint about max file size (in dialog footer)
5b2311 632     $('div.mce-abs-end', dialog.getEl()).append($('<div class="hint">')
AM 633       .text($('div.hint', rcmail.gui_objects.uploadform).text()));
634
635     // init upload button
8f8bea 636     elem = $('#image-upload-button').append($('<span>').text(rcmail.get_label('add' + type)));
5b2311 637     cancel = elem.parents('.mce-panel').find('button:last').parent();
AM 638
639     // we need custom Tab key handlers, until we find out why
640     // tabindex do not work here as expected
641     elem.keydown(function(e) {
642       if (e.which == 9) {
643         // on Tab + Shift focus first file
644         if (rcube_event.get_modifier(e) == SHIFT_KEY)
645           $('#image-selector-list li:last').focus();
646         // on Tab focus Cancel button
647         else
648           cancel.focus();
649
650         return false;
651       }
652     });
653     cancel.keydown(function(e) {
654       if (e.which == 9) {
655         // on Tab + Shift focus upload button
656         if (rcube_event.get_modifier(e) == SHIFT_KEY)
657           elem.focus();
658         else
659           $('#image-selector-list li:first').focus();
660
661         return false;
662       }
663     });
646b64 664
AM 665     // enable (smart) upload button
666     this.hack_file_input(elem, rcmail.gui_objects.uploadform);
667
668     // enable drag-n-drop area
9fa836 669     if ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData) {
AM 670       if (!rcmail.env.filedrop) {
671         rcmail.env.filedrop = {};
672       }
673       if (rcmail.gui_objects.filedrop) {
674         rcmail.env.old_file_drop = rcmail.gui_objects.filedrop;
675       }
676
646b64 677       rcmail.gui_objects.filedrop = $('#image-selector-form');
AM 678       rcmail.gui_objects.filedrop.addClass('droptarget')
d9ff47 679         .on('dragover dragleave', function(e) {
646b64 680           e.preventDefault();
AM 681           e.stopPropagation();
682           $(this)[(e.type == 'dragover' ? 'addClass' : 'removeClass')]('hover');
683         })
684         .get(0).addEventListener('drop', function(e) { return rcmail.file_dropped(e); }, false);
685     }
686
687     // register handler for successful file upload
688     if (!rcmail.env.file_dialog_event) {
689       rcmail.env.file_dialog_event = true;
690       rcmail.addEventListener('fileuploaded', function(attr) {
691         var elem;
692         if (elem = ref.file_browser_entry(attr.name, attr.attachment)) {
693           $('#image-selector-list > ul').prepend(elem);
5b2311 694           elem.focus();
646b64 695         }
AM 696       });
697     }
3cc1af 698
AM 699     // @todo: upload progress indicator
646b64 700   };
AM 701
702   // close file browser window
703   this.file_browser_close = function(url)
704   {
5b2311 705     var input = $('#' + rcmail.env.file_browser_field);
AM 706
646b64 707     if (url)
5b2311 708       input.val(url);
646b64 709
AM 710     this.editor.windowManager.close();
5b2311 711
AM 712     input.focus();
646b64 713
AM 714     if (rcmail.env.old_file_drop)
715       rcmail.gui_objects.filedrop = rcmail.env.old_file_drop;
716   };
717
718   // creates file browser entry
719   this.file_browser_entry = function(file_id, file)
720   {
721     if (!file.complete || !file.mimetype) {
722       return;
9fa836 723     }
AM 724
725     if (rcmail.file_upload_id) {
726       rcmail.set_busy(false, null, rcmail.file_upload_id);
646b64 727     }
AM 728
c5bfe6 729     var rx, img_src;
AM 730
731     switch (rcmail.env.file_browser_type) {
732       case 'image':
733         rx = /^image\//i;
734         break;
735
736       case 'media':
737         rx = /^video\//i;
738         img_src = 'program/js/tinymce/roundcube/video.png';
739         break;
740
741       default:
742         return;
743     }
744
745     if (rx.test(file.mimetype)) {
3cc1af 746       var path = rcmail.env.comm_path + '&_from=' + rcmail.env.action,
AM 747         action = rcmail.env.compose_id ? '&_id=' + rcmail.env.compose_id + '&_action=display-attachment' : '&_action=upload-display',
748         href = path + action + '&_file=' + file_id,
c5bfe6 749         img = $('<img>').attr({title: file.name, src: img_src ? img_src : href + '&_thumbnail=1'});
646b64 750
5b2311 751       return $('<li>').attr({tabindex: 0})
AM 752         .data('url', href)
646b64 753         .append($('<span class="img">').append(img))
AM 754         .append($('<span class="name">').text(file.name))
5b2311 755         .click(function() { ref.file_browser_close($(this).data('url')); })
AM 756         .keydown(function(e) {
757           if (e.which == 13) {
758             ref.file_browser_close($(this).data('url'));
759           }
760           // we need custom Tab key handlers, until we find out why
761           // tabindex do not work here as expected
762           else if (e.which == 9) {
763             if (rcube_event.get_modifier(e) == SHIFT_KEY) {
764               if (!$(this).prev().focus().length)
765                 $('#image-upload-button').parents('.mce-panel').find('button:last').parent().focus();
766             }
767             else {
768               if (!$(this).next().focus().length)
769                 $('#image-upload-button').focus();
770             }
771
772             return false;
773           }
774         });
646b64 775     }
AM 776   };
777
778   // create smart files upload button
779   this.hack_file_input = function(elem, clone_form)
780   {
781     var link = $(elem),
9fa836 782       file = $('<input>').attr('name', '_file[]'),
646b64 783       form = $('<form>').attr({method: 'post', enctype: 'multipart/form-data'}),
AM 784       offset = link.offset();
785
786     // clone existing upload form
787     if (clone_form) {
788       file.attr('name', $('input[type="file"]', clone_form).attr('name'));
789       form.attr('action', $(clone_form).attr('action'))
790         .append($('<input>').attr({type: 'hidden', name: '_token', value: rcmail.env.request_token}));
791     }
792
793     function move_file_input(e) {
794       file.css({top: (e.pageY - offset.top - 10) + 'px', left: (e.pageX - offset.left - 10) + 'px'});
795     }
796
5b2311 797     file.attr({type: 'file', multiple: 'multiple', size: 5, title: '', tabindex: -1})
646b64 798       .change(function() { rcmail.upload_file(form, 'upload'); })
AM 799       .click(function() { setTimeout(function() { link.mouseleave(); }, 20); })
800       // opacity:0 does the trick, display/visibility doesn't work
801       .css({opacity: 0, cursor: 'pointer', position: 'relative', outline: 'none'})
802       .appendTo(form);
803
804     // In FF and IE we need to move the browser file-input's button under the cursor
805     // Thanks to the size attribute above we know the length of the input field
806     if (navigator.userAgent.match(/Firefox|MSIE/))
807       file.css({marginLeft: '-80px'});
808
809     // Note: now, I observe problem with cursor style on FF < 4 only
810     link.css({overflow: 'hidden', cursor: 'pointer'})
811       .mouseenter(function() { this.__active = true; })
812       // place button under the cursor
813       .mousemove(function(e) {
814         if (this.__active)
815           move_file_input(e);
816         // move the input away if button is disabled
817         else
818           $(this).mouseleave();
819       })
820       .mouseleave(function() {
821         file.css({top: '-10000px', left: '-10000px'});
822         this.__active = false;
823       })
824       .click(function(e) {
825         // forward click if mouse-enter event was missed
826         if (!this.__active) {
827           this.__active = true;
828           move_file_input(e);
829           file.trigger(e);
830         }
831       })
5b2311 832       .keydown(function(e) {
AM 833         if (e.which == 13) file.trigger('click');
834       })
646b64 835       .mouseleave()
AM 836       .append(form);
837   };
89d6ce 838 }