Aleksander Machniak
2016-04-24 7abfe41ab792e93b94e186f9ece4a5fd3b58a3e4
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) {
45bfde 453       if (args.selection)
AM 454         text = ed.selection.getContent({format: args.format});
646b64 455
AM 456       if (!text) {
45bfde 457         text = ed.getContent({format: args.format});
AM 458         // @todo: strip signature in html mode
459         strip = args.format == 'text';
646b64 460       }
AM 461     }
462     // get selected text from compose textarea
463     else if (ed = rcube_find_object(this.id)) {
45bfde 464       if (args.selection && $(ed).is(':focus')) {
646b64 465         text = rcmail.get_input_selection(ed).text;
AM 466       }
467
468       if (!text) {
469         text = ed.value;
470         strip = true;
471       }
472     }
473
474     // strip off signature
45bfde 475     // @todo: make this optional
AM 476     if (strip && args.nosig) {
646b64 477       sigstart = text.indexOf('-- \n');
AM 478       if (sigstart > 0) {
479         text = text.substring(0, sigstart);
480       }
481     }
482
483     return text;
484   };
485
486   // change user signature text
487   this.change_signature = function(id, show_sig)
488   {
aa1ddf 489     var position_element, cursor_pos, p = -1,
646b64 490       input_message = $('#' + this.id),
AM 491       message = input_message.val(),
492       sig = rcmail.env.identity;
493
494     if (!this.editor) { // plain text mode
495       // remove the 'old' signature
496       if (show_sig && sig && rcmail.env.signatures && rcmail.env.signatures[sig]) {
497         sig = rcmail.env.signatures[sig].text;
498         sig = sig.replace(/\r\n/g, '\n');
499
500         p = rcmail.env.top_posting ? message.indexOf(sig) : message.lastIndexOf(sig);
501         if (p >= 0)
502           message = message.substring(0, p) + message.substring(p+sig.length, message.length);
503       }
aa1ddf 504
646b64 505       // add the new signature string
AM 506       if (show_sig && rcmail.env.signatures && rcmail.env.signatures[id]) {
507         sig = rcmail.env.signatures[id].text;
508         sig = sig.replace(/\r\n/g, '\n');
509
09225a 510         // in place of removed signature
AM 511         if (p >= 0) {
512           message = message.substring(0, p) + sig + message.substring(p, message.length);
513           cursor_pos = p - 1;
514         }
b0a8e3 515         // empty message or new-message mode
AM 516         else if (!message || !rcmail.env.compose_mode) {
517           cursor_pos = message.length;
518           message += '\n\n' + sig;
09225a 519         }
AM 520         else if (rcmail.env.top_posting && !rcmail.env.sig_below) {
521           // at cursor position
522           if (pos = rcmail.get_caret_pos(input_message.get(0))) {
646b64 523             message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
AM 524             cursor_pos = pos;
525           }
09225a 526           // on top
AM 527           else {
646b64 528             message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
09225a 529             cursor_pos = 0;
646b64 530           }
AM 531         }
532         else {
533           message = message.replace(/[\r\n]+$/, '');
09225a 534           cursor_pos = !rcmail.env.top_posting && message.length ? message.length + 1 : 0;
646b64 535           message += '\n\n' + sig;
AM 536         }
537       }
09225a 538       else {
646b64 539         cursor_pos = rcmail.env.top_posting ? 0 : message.length;
09225a 540       }
646b64 541
AM 542       input_message.val(message);
543
544       // move cursor before the signature
545       rcmail.set_caret_pos(input_message.get(0), cursor_pos);
546     }
547     else if (show_sig && rcmail.env.signatures) {  // html
548       var sigElem = this.editor.dom.get('_rc_sig');
549
550       // Append the signature as a div within the body
551       if (!sigElem) {
bcd379 552         var body = this.editor.getBody();
646b64 553
bcd379 554         sigElem = $('<div id="_rc_sig"></div>').get(0);
646b64 555
bcd379 556         // insert at start or at cursor position in top-posting mode
b0a8e3 557         // (but not if the content is empty and not in new-message mode)
AM 558         if (rcmail.env.top_posting && !rcmail.env.sig_below
559           && rcmail.env.compose_mode && (body.childNodes.length > 1 || $(body).text())
560         ) {
646b64 561           this.editor.getWin().focus(); // correct focus in IE & Chrome
AM 562
563           var node = this.editor.selection.getNode();
09225a 564
bcd379 565           $(sigElem).insertBefore(node.nodeName == 'BODY' ? body.firstChild : node.nextSibling);
AM 566           $('<p>').append($('<br>')).insertBefore(sigElem);
646b64 567         }
AM 568         else {
569           body.appendChild(sigElem);
b0a8e3 570           position_element = rcmail.env.top_posting && rcmail.env.compose_mode ? body.firstChild : $(sigElem).prev();
646b64 571         }
b21f8b 572       }
646b64 573
8449e9 574       sigElem.innerHTML = rcmail.env.signatures[id] ? rcmail.env.signatures[id].html : '';
646b64 575     }
aa1ddf 576     else if (!rcmail.env.top_posting) {
AM 577       position_element = $(this.editor.getBody()).children().last();
578     }
579
580     // put cursor before signature and scroll the window
581     if (this.editor && position_element && position_element.length) {
582       this.editor.selection.setCursorLocation(position_element.get(0));
583       this.editor.getWin().scroll(0, position_element.offset().top);
584     }
646b64 585   };
AM 586
587   // trigger content save
588   this.save = function()
589   {
590     if (this.editor) {
591       this.editor.save();
592     }
593   };
594
595   // focus the editing area
596   this.focus = function()
597   {
598     (this.editor || rcube_find_object(this.id)).focus();
599   };
600
601   // image selector
602   this.file_browser_callback = function(field_name, url, type)
603   {
5b2311 604     var i, elem, cancel, dialog, fn, list = [];
646b64 605
AM 606     // open image selector dialog
607     dialog = this.editor.windowManager.open({
8f8bea 608       title: rcmail.get_label('select' + type),
646b64 609       width: 500,
AM 610       height: 300,
611       html: '<div id="image-selector-list"><ul></ul></div>'
5b2311 612         + '<div id="image-selector-form"><div id="image-upload-button" class="mce-widget mce-btn" role="button" tabindex="0"></div></div>',
646b64 613       buttons: [{text: 'Cancel', onclick: function() { ref.file_browser_close(); }}]
AM 614     });
615
616     rcmail.env.file_browser_field = field_name;
617     rcmail.env.file_browser_type = type;
618
619     // fill images list with available images
620     for (i in rcmail.env.attachments) {
621       if (elem = ref.file_browser_entry(i, rcmail.env.attachments[i])) {
622         list.push(elem);
623       }
624     }
625
626     if (list.length) {
5b2311 627       $('#image-selector-list > ul').append(list).find('li:first').focus();
646b64 628     }
AM 629
630     // add hint about max file size (in dialog footer)
5b2311 631     $('div.mce-abs-end', dialog.getEl()).append($('<div class="hint">')
AM 632       .text($('div.hint', rcmail.gui_objects.uploadform).text()));
633
634     // init upload button
8f8bea 635     elem = $('#image-upload-button').append($('<span>').text(rcmail.get_label('add' + type)));
5b2311 636     cancel = elem.parents('.mce-panel').find('button:last').parent();
AM 637
638     // we need custom Tab key handlers, until we find out why
639     // tabindex do not work here as expected
640     elem.keydown(function(e) {
641       if (e.which == 9) {
642         // on Tab + Shift focus first file
643         if (rcube_event.get_modifier(e) == SHIFT_KEY)
644           $('#image-selector-list li:last').focus();
645         // on Tab focus Cancel button
646         else
647           cancel.focus();
648
649         return false;
650       }
651     });
652     cancel.keydown(function(e) {
653       if (e.which == 9) {
654         // on Tab + Shift focus upload button
655         if (rcube_event.get_modifier(e) == SHIFT_KEY)
656           elem.focus();
657         else
658           $('#image-selector-list li:first').focus();
659
660         return false;
661       }
662     });
646b64 663
AM 664     // enable (smart) upload button
665     this.hack_file_input(elem, rcmail.gui_objects.uploadform);
666
667     // enable drag-n-drop area
9fa836 668     if ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData) {
AM 669       if (!rcmail.env.filedrop) {
670         rcmail.env.filedrop = {};
671       }
672       if (rcmail.gui_objects.filedrop) {
673         rcmail.env.old_file_drop = rcmail.gui_objects.filedrop;
674       }
675
646b64 676       rcmail.gui_objects.filedrop = $('#image-selector-form');
AM 677       rcmail.gui_objects.filedrop.addClass('droptarget')
d9ff47 678         .on('dragover dragleave', function(e) {
646b64 679           e.preventDefault();
AM 680           e.stopPropagation();
681           $(this)[(e.type == 'dragover' ? 'addClass' : 'removeClass')]('hover');
682         })
683         .get(0).addEventListener('drop', function(e) { return rcmail.file_dropped(e); }, false);
684     }
685
686     // register handler for successful file upload
687     if (!rcmail.env.file_dialog_event) {
688       rcmail.env.file_dialog_event = true;
689       rcmail.addEventListener('fileuploaded', function(attr) {
690         var elem;
691         if (elem = ref.file_browser_entry(attr.name, attr.attachment)) {
692           $('#image-selector-list > ul').prepend(elem);
5b2311 693           elem.focus();
646b64 694         }
AM 695       });
696     }
3cc1af 697
AM 698     // @todo: upload progress indicator
646b64 699   };
AM 700
701   // close file browser window
702   this.file_browser_close = function(url)
703   {
5b2311 704     var input = $('#' + rcmail.env.file_browser_field);
AM 705
646b64 706     if (url)
5b2311 707       input.val(url);
646b64 708
AM 709     this.editor.windowManager.close();
5b2311 710
AM 711     input.focus();
646b64 712
AM 713     if (rcmail.env.old_file_drop)
714       rcmail.gui_objects.filedrop = rcmail.env.old_file_drop;
715   };
716
717   // creates file browser entry
718   this.file_browser_entry = function(file_id, file)
719   {
720     if (!file.complete || !file.mimetype) {
721       return;
9fa836 722     }
AM 723
724     if (rcmail.file_upload_id) {
725       rcmail.set_busy(false, null, rcmail.file_upload_id);
646b64 726     }
AM 727
c5bfe6 728     var rx, img_src;
AM 729
730     switch (rcmail.env.file_browser_type) {
731       case 'image':
732         rx = /^image\//i;
733         break;
734
735       case 'media':
736         rx = /^video\//i;
737         img_src = 'program/js/tinymce/roundcube/video.png';
738         break;
739
740       default:
741         return;
742     }
743
744     if (rx.test(file.mimetype)) {
3cc1af 745       var path = rcmail.env.comm_path + '&_from=' + rcmail.env.action,
AM 746         action = rcmail.env.compose_id ? '&_id=' + rcmail.env.compose_id + '&_action=display-attachment' : '&_action=upload-display',
747         href = path + action + '&_file=' + file_id,
c5bfe6 748         img = $('<img>').attr({title: file.name, src: img_src ? img_src : href + '&_thumbnail=1'});
646b64 749
5b2311 750       return $('<li>').attr({tabindex: 0})
AM 751         .data('url', href)
646b64 752         .append($('<span class="img">').append(img))
AM 753         .append($('<span class="name">').text(file.name))
5b2311 754         .click(function() { ref.file_browser_close($(this).data('url')); })
AM 755         .keydown(function(e) {
756           if (e.which == 13) {
757             ref.file_browser_close($(this).data('url'));
758           }
759           // we need custom Tab key handlers, until we find out why
760           // tabindex do not work here as expected
761           else if (e.which == 9) {
762             if (rcube_event.get_modifier(e) == SHIFT_KEY) {
763               if (!$(this).prev().focus().length)
764                 $('#image-upload-button').parents('.mce-panel').find('button:last').parent().focus();
765             }
766             else {
767               if (!$(this).next().focus().length)
768                 $('#image-upload-button').focus();
769             }
770
771             return false;
772           }
773         });
646b64 774     }
AM 775   };
776
777   // create smart files upload button
778   this.hack_file_input = function(elem, clone_form)
779   {
780     var link = $(elem),
9fa836 781       file = $('<input>').attr('name', '_file[]'),
646b64 782       form = $('<form>').attr({method: 'post', enctype: 'multipart/form-data'}),
AM 783       offset = link.offset();
784
785     // clone existing upload form
786     if (clone_form) {
787       file.attr('name', $('input[type="file"]', clone_form).attr('name'));
788       form.attr('action', $(clone_form).attr('action'))
789         .append($('<input>').attr({type: 'hidden', name: '_token', value: rcmail.env.request_token}));
790     }
791
792     function move_file_input(e) {
793       file.css({top: (e.pageY - offset.top - 10) + 'px', left: (e.pageX - offset.left - 10) + 'px'});
794     }
795
5b2311 796     file.attr({type: 'file', multiple: 'multiple', size: 5, title: '', tabindex: -1})
646b64 797       .change(function() { rcmail.upload_file(form, 'upload'); })
AM 798       .click(function() { setTimeout(function() { link.mouseleave(); }, 20); })
799       // opacity:0 does the trick, display/visibility doesn't work
800       .css({opacity: 0, cursor: 'pointer', position: 'relative', outline: 'none'})
801       .appendTo(form);
802
803     // In FF and IE we need to move the browser file-input's button under the cursor
804     // Thanks to the size attribute above we know the length of the input field
805     if (navigator.userAgent.match(/Firefox|MSIE/))
806       file.css({marginLeft: '-80px'});
807
808     // Note: now, I observe problem with cursor style on FF < 4 only
809     link.css({overflow: 'hidden', cursor: 'pointer'})
810       .mouseenter(function() { this.__active = true; })
811       // place button under the cursor
812       .mousemove(function(e) {
813         if (this.__active)
814           move_file_input(e);
815         // move the input away if button is disabled
816         else
817           $(this).mouseleave();
818       })
819       .mouseleave(function() {
820         file.css({top: '-10000px', left: '-10000px'});
821         this.__active = false;
822       })
823       .click(function(e) {
824         // forward click if mouse-enter event was missed
825         if (!this.__active) {
826           this.__active = true;
827           move_file_input(e);
828           file.trigger(e);
829         }
830       })
5b2311 831       .keydown(function(e) {
AM 832         if (e.which == 13) file.trigger('click');
833       })
646b64 834       .mouseleave()
AM 835       .append(form);
836   };
89d6ce 837 }