JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
9a85a84da5502185fdd87382aa8f6ac183c71547
[ckeditor.git] / _source / plugins / selection / plugin.js
1 /*\r
2 Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 (function()\r
7 {\r
8         // #### checkSelectionChange : START\r
9 \r
10         // The selection change check basically saves the element parent tree of\r
11         // the current node and check it on successive requests. If there is any\r
12         // change on the tree, then the selectionChange event gets fired.\r
13         function checkSelectionChange()\r
14         {\r
15                 try\r
16                 {\r
17                         // In IE, the "selectionchange" event may still get thrown when\r
18                         // releasing the WYSIWYG mode, so we need to check it first.\r
19                         var sel = this.getSelection();\r
20                         if ( !sel )\r
21                                 return;\r
22 \r
23                         var firstElement = sel.getStartElement();\r
24                         var currentPath = new CKEDITOR.dom.elementPath( firstElement );\r
25 \r
26                         if ( !currentPath.compare( this._.selectionPreviousPath ) )\r
27                         {\r
28                                 this._.selectionPreviousPath = currentPath;\r
29                                 this.fire( 'selectionChange', { selection : sel, path : currentPath, element : firstElement } );\r
30                         }\r
31                 }\r
32                 catch (e)\r
33                 {}\r
34         }\r
35 \r
36         var checkSelectionChangeTimer,\r
37                 checkSelectionChangeTimeoutPending;\r
38 \r
39         function checkSelectionChangeTimeout()\r
40         {\r
41                 // Firing the "OnSelectionChange" event on every key press started to\r
42                 // be too slow. This function guarantees that there will be at least\r
43                 // 200ms delay between selection checks.\r
44 \r
45                 checkSelectionChangeTimeoutPending = true;\r
46 \r
47                 if ( checkSelectionChangeTimer )\r
48                         return;\r
49 \r
50                 checkSelectionChangeTimeoutExec.call( this );\r
51 \r
52                 checkSelectionChangeTimer = CKEDITOR.tools.setTimeout( checkSelectionChangeTimeoutExec, 200, this );\r
53         }\r
54 \r
55         function checkSelectionChangeTimeoutExec()\r
56         {\r
57                 checkSelectionChangeTimer = null;\r
58 \r
59                 if ( checkSelectionChangeTimeoutPending )\r
60                 {\r
61                         // Call this with a timeout so the browser properly moves the\r
62                         // selection after the mouseup. It happened that the selection was\r
63                         // being moved after the mouseup when clicking inside selected text\r
64                         // with Firefox.\r
65                         CKEDITOR.tools.setTimeout( checkSelectionChange, 0, this );\r
66 \r
67                         checkSelectionChangeTimeoutPending = false;\r
68                 }\r
69         }\r
70 \r
71         // #### checkSelectionChange : END\r
72 \r
73         var selectAllCmd =\r
74         {\r
75                 modes : { wysiwyg : 1, source : 1 },\r
76                 exec : function( editor )\r
77                 {\r
78                         switch ( editor.mode )\r
79                         {\r
80                                 case 'wysiwyg' :\r
81                                         editor.document.$.execCommand( 'SelectAll', false, null );\r
82                                         break;\r
83                                 case 'source' :\r
84                                         // Select the contents of the textarea\r
85                                         var textarea = editor.textarea.$ ;\r
86                                         if ( CKEDITOR.env.ie )\r
87                                         {\r
88                                                 textarea.createTextRange().execCommand( 'SelectAll' ) ;\r
89                                         }\r
90                                         else\r
91                                         {\r
92                                                 textarea.selectionStart = 0 ;\r
93                                                 textarea.selectionEnd = textarea.value.length ;\r
94                                         }\r
95                                         textarea.focus() ;\r
96                         }\r
97                 },\r
98                 canUndo : false\r
99         };\r
100 \r
101         CKEDITOR.plugins.add( 'selection',\r
102         {\r
103                 init : function( editor )\r
104                 {\r
105                         editor.on( 'contentDom', function()\r
106                                 {\r
107                                         var doc = editor.document,\r
108                                                 body = doc.getBody();\r
109 \r
110                                         if ( CKEDITOR.env.ie )\r
111                                         {\r
112                                                 // Other browsers don't loose the selection if the\r
113                                                 // editor document loose the focus. In IE, we don't\r
114                                                 // have support for it, so we reproduce it here, other\r
115                                                 // than firing the selection change event.\r
116 \r
117                                                 var savedRange,\r
118                                                         saveEnabled;\r
119 \r
120                                                 // "onfocusin" is fired before "onfocus". It makes it\r
121                                                 // possible to restore the selection before click\r
122                                                 // events get executed.\r
123                                                 body.on( 'focusin', function( evt )\r
124                                                         {\r
125                                                                 // If there are elements with layout they fire this event but\r
126                                                                 // it must be ignored to allow edit its contents #4682\r
127                                                                 if ( evt.data.$.srcElement.nodeName != 'BODY' )\r
128                                                                         return;\r
129 \r
130                                                                 // If we have saved a range, restore it at this\r
131                                                                 // point.\r
132                                                                 if ( savedRange )\r
133                                                                 {\r
134                                                                         // Well not break because of this.\r
135                                                                         try\r
136                                                                         {\r
137                                                                                 savedRange.select();\r
138                                                                         }\r
139                                                                         catch (e)\r
140                                                                         {}\r
141 \r
142                                                                         savedRange = null;\r
143                                                                 }\r
144                                                         });\r
145 \r
146                                                 body.on( 'focus', function()\r
147                                                         {\r
148                                                                 // Enable selections to be saved.\r
149                                                                 saveEnabled = true;\r
150 \r
151                                                                 saveSelection();\r
152                                                         });\r
153 \r
154                                                 body.on( 'beforedeactivate', function( evt )\r
155                                                         {\r
156                                                                 // Ignore this event if it's caused by focus switch between\r
157                                                                 // internal editable control type elements, e.g. layouted paragraph. (#4682)\r
158                                                                 if ( evt.data.$.toElement )\r
159                                                                         return;\r
160 \r
161                                                                 // Disable selections from being saved.\r
162                                                                 saveEnabled = false;\r
163                                                         });\r
164 \r
165                                                 // IE before version 8 will leave cursor blinking inside the document after\r
166                                                 // editor blurred unless we clean up the selection. (#4716)\r
167                                                 if ( CKEDITOR.env.ie && CKEDITOR.env.version < 8 )\r
168                                                 {\r
169                                                         doc.getWindow().on( 'blur', function( evt )\r
170                                                         {\r
171                                                                 editor.document.$.selection.empty();\r
172                                                         });\r
173                                                 }\r
174 \r
175                                                 // IE fires the "selectionchange" event when clicking\r
176                                                 // inside a selection. We don't want to capture that.\r
177                                                 body.on( 'mousedown', disableSave );\r
178                                                 body.on( 'mouseup',\r
179                                                         function()\r
180                                                         {\r
181                                                                 saveEnabled = true;\r
182                                                                 setTimeout( function()\r
183                                                                         {\r
184                                                                                 saveSelection( true );\r
185                                                                         },\r
186                                                                         0 );\r
187                                                         });\r
188 \r
189                                                 body.on( 'keydown', disableSave );\r
190                                                 body.on( 'keyup',\r
191                                                         function()\r
192                                                         {\r
193                                                                 saveEnabled = true;\r
194                                                                 saveSelection();\r
195                                                         });\r
196 \r
197 \r
198                                                 // IE is the only to provide the "selectionchange"\r
199                                                 // event.\r
200                                                 doc.on( 'selectionchange', saveSelection );\r
201 \r
202                                                 function disableSave()\r
203                                                 {\r
204                                                         saveEnabled = false;\r
205                                                 }\r
206 \r
207                                                 function saveSelection( testIt )\r
208                                                 {\r
209                                                         if ( saveEnabled )\r
210                                                         {\r
211                                                                 var doc = editor.document,\r
212                                                                         sel = doc && doc.$.selection;\r
213 \r
214                                                                 // There is a very specific case, when clicking\r
215                                                                 // inside a text selection. In that case, the\r
216                                                                 // selection collapses at the clicking point,\r
217                                                                 // but the selection object remains in an\r
218                                                                 // unknown state, making createRange return a\r
219                                                                 // range at the very start of the document. In\r
220                                                                 // such situation we have to test the range, to\r
221                                                                 // be sure it's valid.\r
222                                                                 if ( testIt && sel && sel.type == 'None' )\r
223                                                                 {\r
224                                                                         // The "InsertImage" command can be used to\r
225                                                                         // test whether the selection is good or not.\r
226                                                                         // If not, it's enough to give some time to\r
227                                                                         // IE to put things in order for us.\r
228                                                                         if ( !doc.$.queryCommandEnabled( 'InsertImage' ) )\r
229                                                                         {\r
230                                                                                 CKEDITOR.tools.setTimeout( saveSelection, 50, this, true );\r
231                                                                                 return;\r
232                                                                         }\r
233                                                                 }\r
234 \r
235                                                                 savedRange = sel && sel.createRange();\r
236 \r
237                                                                 checkSelectionChangeTimeout.call( editor );\r
238                                                         }\r
239                                                 }\r
240                                         }\r
241                                         else\r
242                                         {\r
243                                                 // In other browsers, we make the selection change\r
244                                                 // check based on other events, like clicks or keys\r
245                                                 // press.\r
246 \r
247                                                 doc.on( 'mouseup', checkSelectionChangeTimeout, editor );\r
248                                                 doc.on( 'keyup', checkSelectionChangeTimeout, editor );\r
249                                         }\r
250                                 });\r
251 \r
252                         editor.addCommand( 'selectAll', selectAllCmd );\r
253                         editor.ui.addButton( 'SelectAll',\r
254                                 {\r
255                                         label : editor.lang.selectAll,\r
256                                         command : 'selectAll'\r
257                                 });\r
258 \r
259                         editor.selectionChange = checkSelectionChangeTimeout;\r
260                 }\r
261         });\r
262 \r
263         /**\r
264          * Gets the current selection from the editing area when in WYSIWYG mode.\r
265          * @returns {CKEDITOR.dom.selection} A selection object or null if not on\r
266          *              WYSIWYG mode or no selection is available.\r
267          * @example\r
268          * var selection = CKEDITOR.instances.editor1.<b>getSelection()</b>;\r
269          * alert( selection.getType() );\r
270          */\r
271         CKEDITOR.editor.prototype.getSelection = function()\r
272         {\r
273                 return this.document && this.document.getSelection();\r
274         };\r
275 \r
276         CKEDITOR.editor.prototype.forceNextSelectionCheck = function()\r
277         {\r
278                 delete this._.selectionPreviousPath;\r
279         };\r
280 \r
281         /**\r
282          * Gets the current selection from the document.\r
283          * @returns {CKEDITOR.dom.selection} A selection object.\r
284          * @example\r
285          * var selection = CKEDITOR.instances.editor1.document.<b>getSelection()</b>;\r
286          * alert( selection.getType() );\r
287          */\r
288         CKEDITOR.dom.document.prototype.getSelection = function()\r
289         {\r
290                 var sel = new CKEDITOR.dom.selection( this );\r
291                 return ( !sel || sel.isInvalid ) ? null : sel;\r
292         };\r
293 \r
294         /**\r
295          * No selection.\r
296          * @constant\r
297          * @example\r
298          * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_NONE )\r
299          *     alert( 'Nothing is selected' );\r
300          */\r
301         CKEDITOR.SELECTION_NONE         = 1;\r
302 \r
303         /**\r
304          * Text or collapsed selection.\r
305          * @constant\r
306          * @example\r
307          * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_TEXT )\r
308          *     alert( 'Text is selected' );\r
309          */\r
310         CKEDITOR.SELECTION_TEXT         = 2;\r
311 \r
312         /**\r
313          * Element selection.\r
314          * @constant\r
315          * @example\r
316          * if ( editor.getSelection().getType() == CKEDITOR.SELECTION_ELEMENT )\r
317          *     alert( 'An element is selected' );\r
318          */\r
319         CKEDITOR.SELECTION_ELEMENT      = 3;\r
320 \r
321         /**\r
322          * Manipulates the selection in a DOM document.\r
323          * @constructor\r
324          * @example\r
325          */\r
326         CKEDITOR.dom.selection = function( document )\r
327         {\r
328                 var lockedSelection = document.getCustomData( 'cke_locked_selection' );\r
329 \r
330                 if ( lockedSelection )\r
331                         return lockedSelection;\r
332 \r
333                 this.document = document;\r
334                 this.isLocked = false;\r
335                 this._ =\r
336                 {\r
337                         cache : {}\r
338                 };\r
339 \r
340                 /**\r
341                  * IE BUG: The selection's document may be a different document than the\r
342                  * editor document. Return null if that's the case.\r
343                  */\r
344                 if ( CKEDITOR.env.ie )\r
345                 {\r
346                         var range = this.getNative().createRange();\r
347                         if ( !range\r
348                                 || ( range.item && range.item(0).ownerDocument != this.document.$ )\r
349                                 || ( range.parentElement && range.parentElement().ownerDocument != this.document.$ ) )\r
350                         {\r
351                                 this.isInvalid = true;\r
352                         }\r
353                 }\r
354 \r
355                 return this;\r
356         };\r
357 \r
358         var styleObjectElements =\r
359         {\r
360                 img:1,hr:1,li:1,table:1,tr:1,td:1,th:1,embed:1,object:1,ol:1,ul:1,\r
361                 a:1, input:1, form:1, select:1, textarea:1, button:1, fieldset:1, th:1, thead:1, tfoot:1\r
362         };\r
363 \r
364         CKEDITOR.dom.selection.prototype =\r
365         {\r
366                 /**\r
367                  * Gets the native selection object from the browser.\r
368                  * @function\r
369                  * @returns {Object} The native selection object.\r
370                  * @example\r
371                  * var selection = editor.getSelection().<b>getNative()</b>;\r
372                  */\r
373                 getNative :\r
374                         CKEDITOR.env.ie ?\r
375                                 function()\r
376                                 {\r
377                                         return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.$.selection );\r
378                                 }\r
379                         :\r
380                                 function()\r
381                                 {\r
382                                         return this._.cache.nativeSel || ( this._.cache.nativeSel = this.document.getWindow().$.getSelection() );\r
383                                 },\r
384 \r
385                 /**\r
386                  * Gets the type of the current selection. The following values are\r
387                  * available:\r
388                  * <ul>\r
389                  *              <li>{@link CKEDITOR.SELECTION_NONE} (1): No selection.</li>\r
390                  *              <li>{@link CKEDITOR.SELECTION_TEXT} (2): Text is selected or\r
391                  *                      collapsed selection.</li>\r
392                  *              <li>{@link CKEDITOR.SELECTION_ELEMENT} (3): A element\r
393                  *                      selection.</li>\r
394                  * </ul>\r
395                  * @function\r
396                  * @returns {Number} One of the following constant values:\r
397                  *              {@link CKEDITOR.SELECTION_NONE}, {@link CKEDITOR.SELECTION_TEXT} or\r
398                  *              {@link CKEDITOR.SELECTION_ELEMENT}.\r
399                  * @example\r
400                  * if ( editor.getSelection().<b>getType()</b> == CKEDITOR.SELECTION_TEXT )\r
401                  *     alert( 'Text is selected' );\r
402                  */\r
403                 getType :\r
404                         CKEDITOR.env.ie ?\r
405                                 function()\r
406                                 {\r
407                                         var cache = this._.cache;\r
408                                         if ( cache.type )\r
409                                                 return cache.type;\r
410 \r
411                                         var type = CKEDITOR.SELECTION_NONE;\r
412 \r
413                                         try\r
414                                         {\r
415                                                 var sel = this.getNative(),\r
416                                                         ieType = sel.type;\r
417 \r
418                                                 if ( ieType == 'Text' )\r
419                                                         type = CKEDITOR.SELECTION_TEXT;\r
420 \r
421                                                 if ( ieType == 'Control' )\r
422                                                         type = CKEDITOR.SELECTION_ELEMENT;\r
423 \r
424                                                 // It is possible that we can still get a text range\r
425                                                 // object even when type == 'None' is returned by IE.\r
426                                                 // So we'd better check the object returned by\r
427                                                 // createRange() rather than by looking at the type.\r
428                                                 if ( sel.createRange().parentElement )\r
429                                                         type = CKEDITOR.SELECTION_TEXT;\r
430                                         }\r
431                                         catch(e) {}\r
432 \r
433                                         return ( cache.type = type );\r
434                                 }\r
435                         :\r
436                                 function()\r
437                                 {\r
438                                         var cache = this._.cache;\r
439                                         if ( cache.type )\r
440                                                 return cache.type;\r
441 \r
442                                         var type = CKEDITOR.SELECTION_TEXT;\r
443 \r
444                                         var sel = this.getNative();\r
445 \r
446                                         if ( !sel )\r
447                                                 type = CKEDITOR.SELECTION_NONE;\r
448                                         else if ( sel.rangeCount == 1 )\r
449                                         {\r
450                                                 // Check if the actual selection is a control (IMG,\r
451                                                 // TABLE, HR, etc...).\r
452 \r
453                                                 var range = sel.getRangeAt(0),\r
454                                                         startContainer = range.startContainer;\r
455 \r
456                                                 if ( startContainer == range.endContainer\r
457                                                         && startContainer.nodeType == 1\r
458                                                         && ( range.endOffset - range.startOffset ) == 1\r
459                                                         && styleObjectElements[ startContainer.childNodes[ range.startOffset ].nodeName.toLowerCase() ] )\r
460                                                 {\r
461                                                         type = CKEDITOR.SELECTION_ELEMENT;\r
462                                                 }\r
463                                         }\r
464 \r
465                                         return ( cache.type = type );\r
466                                 },\r
467 \r
468                 getRanges :\r
469                         CKEDITOR.env.ie ?\r
470                                 ( function()\r
471                                 {\r
472                                         // Finds the container and offset for a specific boundary\r
473                                         // of an IE range.\r
474                                         var getBoundaryInformation = function( range, start )\r
475                                         {\r
476                                                 // Creates a collapsed range at the requested boundary.\r
477                                                 range = range.duplicate();\r
478                                                 range.collapse( start );\r
479 \r
480                                                 // Gets the element that encloses the range entirely.\r
481                                                 var parent = range.parentElement();\r
482                                                 var siblings = parent.childNodes;\r
483 \r
484                                                 var testRange;\r
485 \r
486                                                 for ( var i = 0 ; i < siblings.length ; i++ )\r
487                                                 {\r
488                                                         var child = siblings[ i ];\r
489                                                         if ( child.nodeType == 1 )\r
490                                                         {\r
491                                                                 testRange = range.duplicate();\r
492 \r
493                                                                 testRange.moveToElementText( child );\r
494 \r
495                                                                 var comparisonStart = testRange.compareEndPoints( 'StartToStart', range ),\r
496                                                                         comparisonEnd = testRange.compareEndPoints( 'EndToStart', range );\r
497 \r
498                                                                 testRange.collapse();\r
499 \r
500                                                                 if ( comparisonStart > 0 )\r
501                                                                         break;\r
502                                                                 // When selection stay at the side of certain self-closing elements, e.g. BR,\r
503                                                                 // our comparison will never shows an equality. (#4824)\r
504                                                                 else if ( !comparisonStart\r
505                                                                         || comparisonEnd == 1 && comparisonStart == -1 )\r
506                                                                         return { container : parent, offset : i };\r
507                                                                 else if ( !comparisonEnd )\r
508                                                                         return { container : parent, offset : i + 1 };\r
509 \r
510                                                                 testRange = null;\r
511                                                         }\r
512                                                 }\r
513 \r
514                                                 if ( !testRange )\r
515                                                 {\r
516                                                         testRange = range.duplicate();\r
517                                                         testRange.moveToElementText( parent );\r
518                                                         testRange.collapse( false );\r
519                                                 }\r
520 \r
521                                                 testRange.setEndPoint( 'StartToStart', range );\r
522                                                 // IE report line break as CRLF with range.text but\r
523                                                 // only LF with textnode.nodeValue, normalize them to avoid\r
524                                                 // breaking character counting logic below. (#3949)\r
525                                                 var distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;\r
526 \r
527                                                 try\r
528                                                 {\r
529                                                         while ( distance > 0 )\r
530                                                                 distance -= siblings[ --i ].nodeValue.length;\r
531                                                 }\r
532                                                 // Measurement in IE could be somtimes wrong because of <select> element. (#4611)\r
533                                                 catch( e )\r
534                                                 {\r
535                                                         distance = 0;\r
536                                                 }\r
537 \r
538 \r
539                                                 if ( distance === 0 )\r
540                                                 {\r
541                                                         return {\r
542                                                                 container : parent,\r
543                                                                 offset : i\r
544                                                         };\r
545                                                 }\r
546                                                 else\r
547                                                 {\r
548                                                         return {\r
549                                                                 container : siblings[ i ],\r
550                                                                 offset : -distance\r
551                                                         };\r
552                                                 }\r
553                                         };\r
554 \r
555                                         return function()\r
556                                         {\r
557                                                 var cache = this._.cache;\r
558                                                 if ( cache.ranges )\r
559                                                         return cache.ranges;\r
560 \r
561                                                 // IE doesn't have range support (in the W3C way), so we\r
562                                                 // need to do some magic to transform selections into\r
563                                                 // CKEDITOR.dom.range instances.\r
564 \r
565                                                 var sel = this.getNative(),\r
566                                                         nativeRange = sel && sel.createRange(),\r
567                                                         type = this.getType(),\r
568                                                         range;\r
569 \r
570                                                 if ( !sel )\r
571                                                         return [];\r
572 \r
573                                                 if ( type == CKEDITOR.SELECTION_TEXT )\r
574                                                 {\r
575                                                         range = new CKEDITOR.dom.range( this.document );\r
576 \r
577                                                         var boundaryInfo = getBoundaryInformation( nativeRange, true );\r
578                                                         range.setStart( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );\r
579 \r
580                                                         boundaryInfo = getBoundaryInformation( nativeRange );\r
581                                                         range.setEnd( new CKEDITOR.dom.node( boundaryInfo.container ), boundaryInfo.offset );\r
582 \r
583                                                         return ( cache.ranges = [ range ] );\r
584                                                 }\r
585                                                 else if ( type == CKEDITOR.SELECTION_ELEMENT )\r
586                                                 {\r
587                                                         var retval = this._.cache.ranges = [];\r
588 \r
589                                                         for ( var i = 0 ; i < nativeRange.length ; i++ )\r
590                                                         {\r
591                                                                 var element = nativeRange.item( i ),\r
592                                                                         parentElement = element.parentNode,\r
593                                                                         j = 0;\r
594 \r
595                                                                 range = new CKEDITOR.dom.range( this.document );\r
596 \r
597                                                                 for (; j < parentElement.childNodes.length && parentElement.childNodes[j] != element ; j++ )\r
598                                                                 { /*jsl:pass*/ }\r
599 \r
600                                                                 range.setStart( new CKEDITOR.dom.node( parentElement ), j );\r
601                                                                 range.setEnd( new CKEDITOR.dom.node( parentElement ), j + 1 );\r
602                                                                 retval.push( range );\r
603                                                         }\r
604 \r
605                                                         return retval;\r
606                                                 }\r
607 \r
608                                                 return ( cache.ranges = [] );\r
609                                         };\r
610                                 })()\r
611                         :\r
612                                 function()\r
613                                 {\r
614                                         var cache = this._.cache;\r
615                                         if ( cache.ranges )\r
616                                                 return cache.ranges;\r
617 \r
618                                         // On browsers implementing the W3C range, we simply\r
619                                         // tranform the native ranges in CKEDITOR.dom.range\r
620                                         // instances.\r
621 \r
622                                         var ranges = [];\r
623                                         var sel = this.getNative();\r
624 \r
625                                         if ( !sel )\r
626                                                 return [];\r
627 \r
628                                         for ( var i = 0 ; i < sel.rangeCount ; i++ )\r
629                                         {\r
630                                                 var nativeRange = sel.getRangeAt( i );\r
631                                                 var range = new CKEDITOR.dom.range( this.document );\r
632 \r
633                                                 range.setStart( new CKEDITOR.dom.node( nativeRange.startContainer ), nativeRange.startOffset );\r
634                                                 range.setEnd( new CKEDITOR.dom.node( nativeRange.endContainer ), nativeRange.endOffset );\r
635                                                 ranges.push( range );\r
636                                         }\r
637 \r
638                                         return ( cache.ranges = ranges );\r
639                                 },\r
640 \r
641                 /**\r
642                  * Gets the DOM element in which the selection starts.\r
643                  * @returns {CKEDITOR.dom.element} The element at the beginning of the\r
644                  *              selection.\r
645                  * @example\r
646                  * var element = editor.getSelection().<b>getStartElement()</b>;\r
647                  * alert( element.getName() );\r
648                  */\r
649                 getStartElement : function()\r
650                 {\r
651                         var cache = this._.cache;\r
652                         if ( cache.startElement !== undefined )\r
653                                 return cache.startElement;\r
654 \r
655                         var node,\r
656                                 sel = this.getNative();\r
657 \r
658                         switch ( this.getType() )\r
659                         {\r
660                                 case CKEDITOR.SELECTION_ELEMENT :\r
661                                         return this.getSelectedElement();\r
662 \r
663                                 case CKEDITOR.SELECTION_TEXT :\r
664 \r
665                                         var range = this.getRanges()[0];\r
666 \r
667                                         if ( range )\r
668                                         {\r
669                                                 if ( !range.collapsed )\r
670                                                 {\r
671                                                         range.optimize();\r
672 \r
673                                                         // Decrease the range content to exclude particial\r
674                                                         // selected node on the start which doesn't have\r
675                                                         // visual impact. ( #3231 )\r
676                                                         while ( true )\r
677                                                         {\r
678                                                                 var startContainer = range.startContainer,\r
679                                                                         startOffset = range.startOffset;\r
680                                                                 // Limit the fix only to non-block elements.(#3950)\r
681                                                                 if ( startOffset == ( startContainer.getChildCount ?\r
682                                                                          startContainer.getChildCount() : startContainer.getLength() )\r
683                                                                          && !startContainer.isBlockBoundary() )\r
684                                                                         range.setStartAfter( startContainer );\r
685                                                                 else break;\r
686                                                         }\r
687 \r
688                                                         node = range.startContainer;\r
689 \r
690                                                         if ( node.type != CKEDITOR.NODE_ELEMENT )\r
691                                                                 return node.getParent();\r
692 \r
693                                                         node = node.getChild( range.startOffset );\r
694 \r
695                                                         if ( !node || node.type != CKEDITOR.NODE_ELEMENT )\r
696                                                                 return range.startContainer;\r
697 \r
698                                                         var child = node.getFirst();\r
699                                                         while (  child && child.type == CKEDITOR.NODE_ELEMENT )\r
700                                                         {\r
701                                                                 node = child;\r
702                                                                 child = child.getFirst();\r
703                                                         }\r
704 \r
705                                                         return node;\r
706                                                 }\r
707                                         }\r
708 \r
709                                         if ( CKEDITOR.env.ie )\r
710                                         {\r
711                                                 range = sel.createRange();\r
712                                                 range.collapse( true );\r
713 \r
714                                                 node = range.parentElement();\r
715                                         }\r
716                                         else\r
717                                         {\r
718                                                 node = sel.anchorNode;\r
719 \r
720                                                 if ( node && node.nodeType != 1 )\r
721                                                         node = node.parentNode;\r
722                                         }\r
723                         }\r
724 \r
725                         return cache.startElement = ( node ? new CKEDITOR.dom.element( node ) : null );\r
726                 },\r
727 \r
728                 /**\r
729                  * Gets the current selected element.\r
730                  * @returns {CKEDITOR.dom.element} The selected element. Null if no\r
731                  *              selection is available or the selection type is not\r
732                  *              {@link CKEDITOR.SELECTION_ELEMENT}.\r
733                  * @example\r
734                  * var element = editor.getSelection().<b>getSelectedElement()</b>;\r
735                  * alert( element.getName() );\r
736                  */\r
737                 getSelectedElement : function()\r
738                 {\r
739                         var cache = this._.cache;\r
740                         if ( cache.selectedElement !== undefined )\r
741                                 return cache.selectedElement;\r
742 \r
743                         var self = this;\r
744 \r
745                         var node = CKEDITOR.tools.tryThese(\r
746                                 // Is it native IE control type selection?\r
747                                 function()\r
748                                 {\r
749                                         return self.getNative().createRange().item( 0 );\r
750                                 },\r
751                                 // Figure it out by checking if there's a single enclosed\r
752                                 // node of the range.\r
753                                 function()\r
754                                 {\r
755                                         var range  = self.getRanges()[ 0 ];\r
756                                         range.shrink( CKEDITOR.SHRINK_ELEMENT );\r
757 \r
758                                         var enclosed;\r
759                                         if ( range.startContainer.equals( range.endContainer )\r
760                                                 && ( range.endOffset - range.startOffset ) == 1\r
761                                                 && styleObjectElements[ ( enclosed = range.startContainer.getChild( range.startOffset ) ).getName() ] )\r
762                                         {\r
763                                                 return enclosed.$;\r
764                                         }\r
765                                 });\r
766 \r
767                         return cache.selectedElement = ( node ? new CKEDITOR.dom.element( node ) : null );\r
768                 },\r
769 \r
770                 lock : function()\r
771                 {\r
772                         // Call all cacheable function.\r
773                         this.getRanges();\r
774                         this.getStartElement();\r
775                         this.getSelectedElement();\r
776 \r
777                         // The native selection is not available when locked.\r
778                         this._.cache.nativeSel = {};\r
779 \r
780                         this.isLocked = true;\r
781 \r
782                         // Save this selection inside the DOM document.\r
783                         this.document.setCustomData( 'cke_locked_selection', this );\r
784                 },\r
785 \r
786                 unlock : function( restore )\r
787                 {\r
788                         var doc = this.document,\r
789                                 lockedSelection = doc.getCustomData( 'cke_locked_selection' );\r
790 \r
791                         if ( lockedSelection )\r
792                         {\r
793                                 doc.setCustomData( 'cke_locked_selection', null );\r
794 \r
795                                 if ( restore )\r
796                                 {\r
797                                         var selectedElement = lockedSelection.getSelectedElement(),\r
798                                                 ranges = !selectedElement && lockedSelection.getRanges();\r
799 \r
800                                         this.isLocked = false;\r
801                                         this.reset();\r
802 \r
803                                         doc.getBody().focus();\r
804 \r
805                                         if ( selectedElement )\r
806                                                 this.selectElement( selectedElement );\r
807                                         else\r
808                                                 this.selectRanges( ranges );\r
809                                 }\r
810                         }\r
811 \r
812                         if  ( !lockedSelection || !restore )\r
813                         {\r
814                                 this.isLocked = false;\r
815                                 this.reset();\r
816                         }\r
817                 },\r
818 \r
819                 reset : function()\r
820                 {\r
821                         this._.cache = {};\r
822                 },\r
823 \r
824                 selectElement : function( element )\r
825                 {\r
826                         if ( this.isLocked )\r
827                         {\r
828                                 var range = new CKEDITOR.dom.range( this.document );\r
829                                 range.setStartBefore( element );\r
830                                 range.setEndAfter( element );\r
831 \r
832                                 this._.cache.selectedElement = element;\r
833                                 this._.cache.startElement = element;\r
834                                 this._.cache.ranges = [ range ];\r
835                                 this._.cache.type = CKEDITOR.SELECTION_ELEMENT;\r
836 \r
837                                 return;\r
838                         }\r
839 \r
840                         if ( CKEDITOR.env.ie )\r
841                         {\r
842                                 this.getNative().empty();\r
843 \r
844                                 try\r
845                                 {\r
846                                         // Try to select the node as a control.\r
847                                         range = this.document.$.body.createControlRange();\r
848                                         range.addElement( element.$ );\r
849                                         range.select();\r
850                                 }\r
851                                 catch(e)\r
852                                 {\r
853                                         // If failed, select it as a text range.\r
854                                         range = this.document.$.body.createTextRange();\r
855                                         range.moveToElementText( element.$ );\r
856                                         range.select();\r
857                                 }\r
858                                 finally\r
859                                 {\r
860                                         this.document.fire( 'selectionchange' );\r
861                                 }\r
862 \r
863                                 this.reset();\r
864                         }\r
865                         else\r
866                         {\r
867                                 // Create the range for the element.\r
868                                 range = this.document.$.createRange();\r
869                                 range.selectNode( element.$ );\r
870 \r
871                                 // Select the range.\r
872                                 var sel = this.getNative();\r
873                                 sel.removeAllRanges();\r
874                                 sel.addRange( range );\r
875 \r
876                                 this.reset();\r
877                         }\r
878                 },\r
879 \r
880                 selectRanges : function( ranges )\r
881                 {\r
882                         if ( this.isLocked )\r
883                         {\r
884                                 this._.cache.selectedElement = null;\r
885                                 this._.cache.startElement = ranges[ 0 ].getTouchedStartNode();\r
886                                 this._.cache.ranges = ranges;\r
887                                 this._.cache.type = CKEDITOR.SELECTION_TEXT;\r
888 \r
889                                 return;\r
890                         }\r
891 \r
892                         if ( CKEDITOR.env.ie )\r
893                         {\r
894                                 // IE doesn't accept multiple ranges selection, so we just\r
895                                 // select the first one.\r
896                                 if ( ranges[ 0 ] )\r
897                                         ranges[ 0 ].select();\r
898 \r
899                                 this.reset();\r
900                         }\r
901                         else\r
902                         {\r
903                                 var sel = this.getNative();\r
904                                 sel.removeAllRanges();\r
905 \r
906                                 for ( var i = 0 ; i < ranges.length ; i++ )\r
907                                 {\r
908                                         var range = ranges[ i ];\r
909                                         var nativeRange = this.document.$.createRange();\r
910                                         var startContainer = range.startContainer;\r
911 \r
912                                         // In FF2, if we have a collapsed range, inside an empty\r
913                                         // element, we must add something to it otherwise the caret\r
914                                         // will not be visible.\r
915                                         if ( range.collapsed &&\r
916                                                 ( CKEDITOR.env.gecko && CKEDITOR.env.version < 10900 ) &&\r
917                                                 startContainer.type == CKEDITOR.NODE_ELEMENT &&\r
918                                                 !startContainer.getChildCount() )\r
919                                         {\r
920                                                 startContainer.appendText( '' );\r
921                                         }\r
922 \r
923                                         nativeRange.setStart( startContainer.$, range.startOffset );\r
924                                         nativeRange.setEnd( range.endContainer.$, range.endOffset );\r
925 \r
926                                         // Select the range.\r
927                                         sel.addRange( nativeRange );\r
928                                 }\r
929 \r
930                                 this.reset();\r
931                         }\r
932                 },\r
933 \r
934                 createBookmarks : function( serializable )\r
935                 {\r
936                         var retval = [],\r
937                                 ranges = this.getRanges(),\r
938                                 length = ranges.length,\r
939                                 bookmark;\r
940                         for ( var i = 0; i < length ; i++ )\r
941                         {\r
942                             retval.push( bookmark = ranges[ i ].createBookmark( serializable, true ) );\r
943 \r
944                                 serializable = bookmark.serializable;\r
945 \r
946                                 var bookmarkStart = serializable ? this.document.getById( bookmark.startNode ) : bookmark.startNode,\r
947                                         bookmarkEnd = serializable ? this.document.getById( bookmark.endNode ) : bookmark.endNode;\r
948 \r
949                             // Updating the offset values for rest of ranges which have been mangled(#3256).\r
950                             for ( var j = i + 1 ; j < length ; j++ )\r
951                             {\r
952                                 var dirtyRange = ranges[ j ],\r
953                                        rangeStart = dirtyRange.startContainer,\r
954                                        rangeEnd = dirtyRange.endContainer;\r
955 \r
956                                rangeStart.equals( bookmarkStart.getParent() ) && dirtyRange.startOffset++;\r
957                                rangeStart.equals( bookmarkEnd.getParent() ) && dirtyRange.startOffset++;\r
958                                rangeEnd.equals( bookmarkStart.getParent() ) && dirtyRange.endOffset++;\r
959                                rangeEnd.equals( bookmarkEnd.getParent() ) && dirtyRange.endOffset++;\r
960                             }\r
961                         }\r
962 \r
963                         return retval;\r
964                 },\r
965 \r
966                 createBookmarks2 : function( normalized )\r
967                 {\r
968                         var bookmarks = [],\r
969                                 ranges = this.getRanges();\r
970 \r
971                         for ( var i = 0 ; i < ranges.length ; i++ )\r
972                                 bookmarks.push( ranges[i].createBookmark2( normalized ) );\r
973 \r
974                         return bookmarks;\r
975                 },\r
976 \r
977                 selectBookmarks : function( bookmarks )\r
978                 {\r
979                         var ranges = [];\r
980                         for ( var i = 0 ; i < bookmarks.length ; i++ )\r
981                         {\r
982                                 var range = new CKEDITOR.dom.range( this.document );\r
983                                 range.moveToBookmark( bookmarks[i] );\r
984                                 ranges.push( range );\r
985                         }\r
986                         this.selectRanges( ranges );\r
987                         return this;\r
988                 },\r
989 \r
990                 getCommonAncestor : function()\r
991                 {\r
992                         var ranges = this.getRanges(),\r
993                                 startNode = ranges[ 0 ].startContainer,\r
994                                 endNode = ranges[ ranges.length - 1 ].endContainer;\r
995                         return startNode.getCommonAncestor( endNode );\r
996                 },\r
997 \r
998                 // Moving scroll bar to the current selection's start position.\r
999                 scrollIntoView : function()\r
1000                 {\r
1001                         // If we have split the block, adds a temporary span at the\r
1002                         // range position and scroll relatively to it.\r
1003                         var start = this.getStartElement();\r
1004                         start.scrollIntoView();\r
1005                 }\r
1006         };\r
1007 })();\r
1008 ( function()\r
1009 {\r
1010 var notWhitespaces = CKEDITOR.dom.walker.whitespaces( true );\r
1011 var fillerTextRegex = /\ufeff|\u00a0/;\r
1012 \r
1013 CKEDITOR.dom.range.prototype.select =\r
1014         CKEDITOR.env.ie ?\r
1015                 // V2\r
1016                 function( forceExpand )\r
1017                 {\r
1018                         var collapsed = this.collapsed;\r
1019                         var isStartMarkerAlone;\r
1020                         var dummySpan;\r
1021 \r
1022                         var bookmark = this.createBookmark();\r
1023 \r
1024                         // Create marker tags for the start and end boundaries.\r
1025                         var startNode = bookmark.startNode;\r
1026 \r
1027                         var endNode;\r
1028                         if ( !collapsed )\r
1029                                 endNode = bookmark.endNode;\r
1030 \r
1031                         // Create the main range which will be used for the selection.\r
1032                         var ieRange = this.document.$.body.createTextRange();\r
1033 \r
1034                         // Position the range at the start boundary.\r
1035                         ieRange.moveToElementText( startNode.$ );\r
1036                         ieRange.moveStart( 'character', 1 );\r
1037 \r
1038                         if ( endNode )\r
1039                         {\r
1040                                 // Create a tool range for the end.\r
1041                                 var ieRangeEnd = this.document.$.body.createTextRange();\r
1042 \r
1043                                 // Position the tool range at the end.\r
1044                                 ieRangeEnd.moveToElementText( endNode.$ );\r
1045 \r
1046                                 // Move the end boundary of the main range to match the tool range.\r
1047                                 ieRange.setEndPoint( 'EndToEnd', ieRangeEnd );\r
1048                                 ieRange.moveEnd( 'character', -1 );\r
1049                         }\r
1050                         else\r
1051                         {\r
1052                                 // The isStartMarkerAlone logic comes from V2. It guarantees that the lines\r
1053                                 // will expand and that the cursor will be blinking on the right place.\r
1054                                 // Actually, we are using this flag just to avoid using this hack in all\r
1055                                 // situations, but just on those needed.\r
1056                                 var next = startNode.getNext( notWhitespaces );\r
1057                                 isStartMarkerAlone = ( !( next && next.getText && next.getText().match( fillerTextRegex ) )     // already a filler there?\r
1058                                                                           && ( forceExpand || !startNode.hasPrevious() || ( startNode.getPrevious().is && startNode.getPrevious().is( 'br' ) ) ) );\r
1059 \r
1060                                 // Append a temporary <span>&#65279;</span> before the selection.\r
1061                                 // This is needed to avoid IE destroying selections inside empty\r
1062                                 // inline elements, like <b></b> (#253).\r
1063                                 // It is also needed when placing the selection right after an inline\r
1064                                 // element to avoid the selection moving inside of it.\r
1065                                 dummySpan = this.document.createElement( 'span' );\r
1066                                 dummySpan.setHtml( '&#65279;' );        // Zero Width No-Break Space (U+FEFF). See #1359.\r
1067                                 dummySpan.insertBefore( startNode );\r
1068 \r
1069                                 if ( isStartMarkerAlone )\r
1070                                 {\r
1071                                         // To expand empty blocks or line spaces after <br>, we need\r
1072                                         // instead to have any char, which will be later deleted using the\r
1073                                         // selection.\r
1074                                         // \ufeff = Zero Width No-Break Space (U+FEFF). (#1359)\r
1075                                         this.document.createText( '\ufeff' ).insertBefore( startNode );\r
1076                                 }\r
1077                         }\r
1078 \r
1079                         // Remove the markers (reset the position, because of the changes in the DOM tree).\r
1080                         this.setStartBefore( startNode );\r
1081                         startNode.remove();\r
1082 \r
1083                         if ( collapsed )\r
1084                         {\r
1085                                 if ( isStartMarkerAlone )\r
1086                                 {\r
1087                                         // Move the selection start to include the temporary \ufeff.\r
1088                                         ieRange.moveStart( 'character', -1 );\r
1089 \r
1090                                         ieRange.select();\r
1091 \r
1092                                         // Remove our temporary stuff.\r
1093                                         this.document.$.selection.clear();\r
1094                                 }\r
1095                                 else\r
1096                                         ieRange.select();\r
1097 \r
1098                                 this.moveToPosition( dummySpan, CKEDITOR.POSITION_BEFORE_START );\r
1099                                 dummySpan.remove();\r
1100                         }\r
1101                         else\r
1102                         {\r
1103                                 this.setEndBefore( endNode );\r
1104                                 endNode.remove();\r
1105                                 ieRange.select();\r
1106                         }\r
1107 \r
1108                         this.document.fire( 'selectionchange' );\r
1109                 }\r
1110         :\r
1111                 function()\r
1112                 {\r
1113                         var startContainer = this.startContainer;\r
1114 \r
1115                         // If we have a collapsed range, inside an empty element, we must add\r
1116                         // something to it, otherwise the caret will not be visible.\r
1117                         if ( this.collapsed && startContainer.type == CKEDITOR.NODE_ELEMENT && !startContainer.getChildCount() )\r
1118                                 startContainer.append( new CKEDITOR.dom.text( '' ) );\r
1119 \r
1120                         var nativeRange = this.document.$.createRange();\r
1121                         nativeRange.setStart( startContainer.$, this.startOffset );\r
1122 \r
1123                         try\r
1124                         {\r
1125                                 nativeRange.setEnd( this.endContainer.$, this.endOffset );\r
1126                         }\r
1127                         catch ( e )\r
1128                         {\r
1129                                 // There is a bug in Firefox implementation (it would be too easy\r
1130                                 // otherwise). The new start can't be after the end (W3C says it can).\r
1131                                 // So, let's create a new range and collapse it to the desired point.\r
1132                                 if ( e.toString().indexOf( 'NS_ERROR_ILLEGAL_VALUE' ) >= 0 )\r
1133                                 {\r
1134                                         this.collapse( true );\r
1135                                         nativeRange.setEnd( this.endContainer.$, this.endOffset );\r
1136                                 }\r
1137                                 else\r
1138                                         throw( e );\r
1139                         }\r
1140 \r
1141                         var selection = this.document.getSelection().getNative();\r
1142                         selection.removeAllRanges();\r
1143                         selection.addRange( nativeRange );\r
1144                 };\r
1145 } )();\r