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