Files
WebODF/webodf/lib/ops/OdtDocument.js
T
Philip Peitsch dd166cb00c Refactor getPostionInTextNode to use cached step information
The new implementation should be equivalent in every way, except
it now is able to benefit from the cached step information to be
significantly more faster.

This patch also addresses parts of issue #3.
2013-11-14 20:28:36 +11:00

750 lines
28 KiB
JavaScript

/**
* @license
* Copyright (C) 2012-2013 KO GmbH <copyright@kogmbh.com>
*
* @licstart
* The JavaScript code in this page is free software: you can redistribute it
* and/or modify it under the terms of the GNU Affero General Public License
* (GNU AGPL) as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. The code is distributed
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU AGPL for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this code. If not, see <http://www.gnu.org/licenses/>.
*
* As additional permission under GNU AGPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* As a special exception to the AGPL, any HTML file which merely makes function
* calls to this code, and for that purpose includes it by reference shall be
* deemed a separate work for copyright law purposes. In addition, the copyright
* holders of this code give you permission to combine this code with free
* software libraries that are released under the GNU LGPL. You may copy and
* distribute such a system following the terms of the GNU AGPL for this code
* and the LGPL for the libraries. If you modify this code, you may extend this
* exception to your version of the code, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your
* version.
*
* This license applies to this entire compilation.
* @licend
* @source: http://www.webodf.org/
* @source: https://github.com/kogmbh/WebODF/
*/
/*global Node, runtime, core, gui, ops, odf*/
runtime.loadClass("core.EventNotifier");
runtime.loadClass("core.DomUtils");
runtime.loadClass("odf.OdfUtils");
runtime.loadClass("odf.Namespaces");
runtime.loadClass("gui.SelectionMover");
runtime.loadClass("core.PositionFilterChain");
runtime.loadClass("ops.StepsTranslator");
runtime.loadClass("ops.TextPositionFilter");
/**
* A document that keeps all data related to the mapped document.
* @constructor
* @param {!odf.OdfCanvas} odfCanvas
*/
ops.OdtDocument = function OdtDocument(odfCanvas) {
"use strict";
var self = this,
odfUtils,
domUtils,
/**!Object.<!ops.OdtCursor>*/cursors = {},
eventNotifier = new core.EventNotifier([
ops.OdtDocument.signalCursorAdded,
ops.OdtDocument.signalCursorRemoved,
ops.OdtDocument.signalCursorMoved,
ops.OdtDocument.signalParagraphChanged,
ops.OdtDocument.signalParagraphStyleModified,
ops.OdtDocument.signalCommonStyleCreated,
ops.OdtDocument.signalCommonStyleDeleted,
ops.OdtDocument.signalTableAdded,
ops.OdtDocument.signalOperationExecuted,
ops.OdtDocument.signalUndoStackChanged,
ops.OdtDocument.signalStepsInserted,
ops.OdtDocument.signalStepsRemoved
]),
/**@const*/FILTER_ACCEPT = core.PositionFilter.FilterResult.FILTER_ACCEPT,
/**@const*/FILTER_REJECT = core.PositionFilter.FilterResult.FILTER_REJECT,
filter,
stepsTranslator;
/**
* @return {!Element}
*/
function getRootNode() {
var element = odfCanvas.odfContainer().getContentElement(),
localName = element && element.localName;
runtime.assert(localName === "text", "Unsupported content element type '" + localName + "' for OdtDocument");
return element;
}
/**
* @return {!Document}
*/
function getDOM() {
return /**@type{!Document}*/(getRootNode().ownerDocument);
}
this.getDOM = getDOM;
/**
* @param {!Node} node
* @return {!boolean}
*/
function isRoot(node) {
if ((node.namespaceURI === odf.Namespaces.officens && node.localName === 'text') ||
(node.namespaceURI === odf.Namespaces.officens && node.localName === 'annotation')) {
return true;
}
return false;
}
/**
* @param {!Node} node
* @return {!Node}
*/
function getRoot(node) {
while (node && !isRoot(node)) {
node = /**@type{!Node}*/(node.parentNode);
}
return node;
}
this.getRootElement = getRoot;
/**
* A filter that allows a position if it has the same closest
* whitelisted root as the specified 'anchor', which can be the cursor
* of the given memberid, or a given node
* @constructor
* @implements {core.PositionFilter}
* @param {!string|!Node} anchor
*/
function RootFilter(anchor) {
/**
* @param {!core.PositionIterator} iterator
* @return {!core.PositionFilter.FilterResult}
*/
this.acceptPosition = function (iterator) {
var node = iterator.container(),
anchorNode;
if (typeof anchor === "string") {
anchorNode = cursors[anchor].getNode();
} else {
anchorNode = anchor;
}
if (getRoot(node) === getRoot(anchorNode)) {
return FILTER_ACCEPT;
}
return FILTER_REJECT;
};
}
/**
* Returns a PositionIterator instance at the
* specified starting position
* @param {!number} position
* @return {!core.PositionIterator}
*/
function getIteratorAtPosition(position) {
var iterator = gui.SelectionMover.createPositionIterator(getRootNode()),
point = stepsTranslator.convertStepsToDomPoint(position);
iterator.setUnfilteredPosition(point.node, point.offset);
return iterator;
}
this.getIteratorAtPosition = getIteratorAtPosition;
/**
*
* @param {!Node} node
* @param {!number} offset
* @returns {!number}
*/
this.convertDomPointToCursorStep = function(node, offset) {
return stepsTranslator.convertDomPointToSteps(node, offset);
};
/**
*
* @param {!Node} anchorNode
* @param {!number} anchorOffset
* @param {!Node} focusNode
* @param {!number} focusOffset
* @returns {{position: !number, length: number}}
*/
this.convertDomToCursorRange = function(anchorNode, anchorOffset, focusNode, focusOffset) {
var point1,
point2;
point1 = stepsTranslator.convertDomPointToSteps(anchorNode, anchorOffset);
if (anchorNode === focusNode && anchorOffset === focusOffset) {
point2 = point1;
} else {
point2 = stepsTranslator.convertDomPointToSteps(focusNode, focusOffset);
}
return {
position: point1,
length: point2 - point1
};
};
/**
* Convert a cursor range to a DOM range
* @param {!number} position
* @param {!number} length
* @returns {Range}
*/
this.convertCursorToDomRange = function(position, length) {
var range = getDOM().createRange(),
point1,
point2;
point1 = stepsTranslator.convertStepsToDomPoint(position);
if (length) {
point2 = stepsTranslator.convertStepsToDomPoint(position + length);
if (length > 0) {
range.setStart(point1.node, point1.offset);
range.setEnd(point2.node, point2.offset);
} else {
range.setStart(point2.node, point2.offset);
range.setEnd(point1.node, point1.offset);
}
} else {
range.setStart(point1.node, point1.offset);
}
return range;
};
/**
* This function will iterate through positions allowed by the position
* iterator and count only the text positions. When the amount defined by
* offset has been counted, the Text node that that position is returned
* as well as the offset in that text node.
* Optionally takes a memberid of a cursor, to specifically return the
* text node positioned just behind that cursor.
* @param {!number} steps
* @param {!string=} memberid
* @return {?{textNode: !Text, offset: !number}}
*/
function getTextNodeAtStep(steps, memberid) {
var iterator = getIteratorAtPosition(steps),
node = iterator.container(),
lastTextNode,
nodeOffset = 0,
cursorNode = null;
if (node.nodeType === Node.TEXT_NODE) {
// Iterator has stopped within an existing text node, to put that up as a possible target node
lastTextNode = /**@type{!Text}*/(node);
nodeOffset = iterator.unfilteredDomOffset();
} else {
// There is no text node at the current position, so insert a new one at the current position
lastTextNode = getDOM().createTextNode("");
nodeOffset = 0;
node.insertBefore(lastTextNode, iterator.rightNode());
}
// If the member cursor is as the requested position
if (memberid && cursors[memberid] && self.getCursorPosition(memberid) === steps) {
cursorNode = cursors[memberid].getNode();
// Then move the member's cursor after all adjacent cursors
while (cursorNode.nextSibling && cursorNode.nextSibling.localName === "cursor") {
// TODO this re-arrange logic will break if there are non-cursor elements in the way
// E.g., cursors occupy the same "step", but are on different sides of a span boundary
// This is currently avoided by calling fixCursorPositions after (almost) every op
// to re-arrange cursors together again
cursorNode.parentNode.insertBefore(cursorNode.nextSibling, cursorNode);
}
if (lastTextNode.length > 0 && lastTextNode.nextSibling !== cursorNode) {
// The last text node contains content but is not adjacent to the cursor
// This can't be moved, as moving it would move the text content around as well. Yikes!
// So, create a new text node to insert data into
lastTextNode = getDOM().createTextNode('');
nodeOffset = 0;
}
// Keep the destination text node right next to the member's cursor, so inserted text pushes the cursor over
cursorNode.parentNode.insertBefore(lastTextNode, cursorNode);
}
// After the above cursor-specific adjustment, if the lastTextNode
// has a text node previousSibling, merge them and make the result the lastTextNode
while (lastTextNode.previousSibling && lastTextNode.previousSibling.nodeType === Node.TEXT_NODE) {
lastTextNode.previousSibling.appendData(lastTextNode.data);
nodeOffset = lastTextNode.previousSibling.length;
lastTextNode = /**@type{!Text}*/(lastTextNode.previousSibling);
lastTextNode.parentNode.removeChild(lastTextNode.nextSibling);
}
return {textNode: lastTextNode, offset: nodeOffset };
}
/**
* @param {?Node} node
* @return {?Node}
*/
function getParagraphElement(node) {
return odfUtils.getParagraphElement(node);
}
/**
* @param {!string} styleName
* @param {!string} styleFamily
* @returns {Element}
*/
function getStyleElement(styleName, styleFamily) {
return odfCanvas.getFormatting().getStyleElement(styleName, styleFamily);
}
this.getStyleElement = getStyleElement;
/**
* @param {!string} styleName
* @return {Element}
*/
function getParagraphStyleElement(styleName) {
return getStyleElement(styleName, 'paragraph');
}
/**
* @param {!string} styleName
* @return {?Object}
*/
function getParagraphStyleAttributes(styleName) {
var node = getParagraphStyleElement(styleName);
if (node) {
return odfCanvas.getFormatting().getInheritedStyleAttributes(node);
}
return null;
}
/**
* Upgrades literal whitespaces (' ') to <text:s> </text:s>,
* when given a textNode containing the whitespace and an offset
* indicating the location of the whitespace in it.
* @param {!Text} textNode
* @param {!number} offset
* @return {!Element}
*/
function upgradeWhitespaceToElement(textNode, offset) {
runtime.assert(textNode.data[offset] === ' ', "upgradeWhitespaceToElement: textNode.data[offset] should be a literal space");
var space = textNode.ownerDocument.createElementNS(odf.Namespaces.textns, 'text:s');
space.appendChild(textNode.ownerDocument.createTextNode(' '));
textNode.deleteData(offset, 1);
if (offset > 0) { // Don't create an empty text node if the offset is 0...
textNode = /**@type {!Text}*/(textNode.splitText(offset));
}
textNode.parentNode.insertBefore(space, textNode);
return space;
}
function upgradeWhitespacesAtPosition(position) {
var iterator = getIteratorAtPosition(position),
container,
offset,
i;
// Ideally we have to check from *two* positions to the left and right
// because the position may be surrounded by node boundaries. Slightly hackish.
iterator.previousPosition();
iterator.previousPosition();
for (i = -1; i <= 1; i += 1) {
container = iterator.container();
offset = iterator.unfilteredDomOffset();
if (container.nodeType === Node.TEXT_NODE
&& container.data[offset] === ' '
&& odfUtils.isSignificantWhitespace(container, offset)) {
container = upgradeWhitespaceToElement(/**@type{!Text}*/(container), offset);
// Reset the iterator position to be after the newly created space character
iterator.moveToEndOfNode(container);
}
iterator.nextPosition();
}
}
/**
* Upgrades any significant whitespace at, one step left, and one step right of the given
* position to space elements.
* @param {!number} position
* @return {undefined}
*/
this.upgradeWhitespacesAtPosition = upgradeWhitespacesAtPosition;
/**
* Downgrades white space elements to normal spaces at the specified position if possible
* @param {!number} position
*/
this.downgradeWhitespacesAtPosition = function (position) {
var iterator = getIteratorAtPosition(position),
container,
offset,
firstSpaceElementChild, lastSpaceElementChild;
container = iterator.container();
offset = iterator.unfilteredDomOffset();
while (!odfUtils.isCharacterElement(container) && container.childNodes[offset]) {
// iterator.container will likely return a paragraph element with a non-zero offset
// easiest way to translate this is to keep diving into child nodes until the either
// an odf character element is encountered, or there are no more children
container = container.childNodes[offset];
offset = 0;
}
if (container.nodeType === Node.TEXT_NODE) {
// a space element cannot be a text node. Perhaps it's parent is
// this would be hit if iterator.container returns a text node or the previous loop dives
// all the way down without finding any odf character elements
container = container.parentNode;
}
if (odfUtils.isDowngradableSpaceElement(container)) {
firstSpaceElementChild = container.firstChild;
lastSpaceElementChild = container.lastChild;
domUtils.mergeIntoParent(container);
// merge any now neighbouring textnodes
// usually there was just one child node, " "
if (lastSpaceElementChild !== firstSpaceElementChild) {
domUtils.normalizeTextNodes(lastSpaceElementChild);
}
domUtils.normalizeTextNodes(firstSpaceElementChild);
}
};
this.getParagraphStyleElement = getParagraphStyleElement;
this.getParagraphElement = getParagraphElement;
/**
* This method returns the style attributes for a given stylename, including all properties
* inherited from any parent styles, and also the Default style in the family.
* @param {!string} styleName
* @return {?Object}
*/
this.getParagraphStyleAttributes = getParagraphStyleAttributes;
/**
* This function will return the Text node as well as the offset in that text node
* of the cursor.
* @param {!number} position
* @param {!string=} memberid
* @return {?{textNode: !Text, offset: !number}}
*/
this.getTextNodeAtStep = getTextNodeAtStep;
/**
* Iterates through all cursors and checks if they are in
* walkable positions; if not, move the cursor 1 filtered step backward
* which guarantees walkable state for all cursors,
* while keeping them inside the same root. An event will be raised for this cursor if it is moved
*/
this.fixCursorPositions = function () {
var rootConstrainedFilter = new core.PositionFilterChain();
rootConstrainedFilter.addFilter('BaseFilter', filter);
Object.keys(cursors).forEach(function(memberId) {
var cursor = cursors[memberId],
stepCounter = cursor.getStepCounter(),
stepsSelectionLength,
positionsToAdjustFocus,
positionsToAdjustAnchor,
positionsToAnchor,
cursorMoved = false;
// Equip a Root Filter for specifically this cursor
rootConstrainedFilter.addFilter('RootFilter', self.createRootFilter(memberId));
stepsSelectionLength = stepCounter.countStepsToPosition(cursor.getAnchorNode(), 0, rootConstrainedFilter);
if (!stepCounter.isPositionWalkable(rootConstrainedFilter)) {
cursorMoved = true;
// Record how far off each end of the selection is from an accepted position
positionsToAdjustFocus = stepCounter.countPositionsToNearestStep(cursor.getNode(), 0, rootConstrainedFilter);
positionsToAdjustAnchor = stepCounter.countPositionsToNearestStep(cursor.getAnchorNode(), 0, rootConstrainedFilter);
cursor.move(positionsToAdjustFocus); // Need to move into a valid position before extending the selection
if (stepsSelectionLength !== 0) {
// Normally the step is rounded down, meaning the position adjustment will be negative
// The only circumstance in which the position adjust is positive is when either the node appears
// before the first valid position in a document, or, the rounded down position would move the node
// to a previous paragraph (something that is never desired)
// In this case, the selection is lengthened or shortened when the anchor and focus are adjusted
if (positionsToAdjustAnchor > 0) {
stepsSelectionLength += 1;
}
if (positionsToAdjustFocus > 0) {
stepsSelectionLength -= 1;
}
positionsToAnchor = stepCounter.countSteps(stepsSelectionLength, rootConstrainedFilter);
// Cursor extension implicitly goes anchor-to-focus. As such, the cursor needs to be navigated
// first to the anchor position, then extended to the focus node to ensure the focus ends up at the
// correct end of the selection
cursor.move(positionsToAnchor);
cursor.move(-positionsToAnchor, true);
}
} else if (stepsSelectionLength === 0) {
cursorMoved = true;
// call move(0) here to force the cursor to reset its selection to collapsed
// and remove the now-unnecessary anchor node
cursor.move(0);
}
if (cursorMoved) {
self.emit(ops.OdtDocument.signalCursorMoved, cursor);
}
// Un-equip the Root Filter for this cursor because we are done with it
rootConstrainedFilter.removeFilter('RootFilter');
});
};
/**
* This function calculates the steps in ODF world between the cursor of the
* given member and the given position in the DOM. If the given position is
* not walkable, then it will be the number of steps to the last walkable position
* before the given position from the direction of the cursor.
* @param {!string} memberid
* @param {!Node} node
* @param {!number} offset offset in filtered DOM world
* @return {!number}
*/
this.getDistanceFromCursor = function (memberid, node, offset) {
var cursor = cursors[memberid],
focusPosition,
targetPosition;
runtime.assert((node !== null) && (node !== undefined),
"OdtDocument.getDistanceFromCursor called without node");
if (cursor) {
focusPosition = stepsTranslator.convertDomPointToSteps(cursor.getNode(), 0);
targetPosition = stepsTranslator.convertDomPointToSteps(node, offset);
}
return targetPosition - focusPosition;
};
/**
* This function returns the position in ODF world of the cursor of the member.
* @param {!string} memberid
* @return {!number}
*/
this.getCursorPosition = function (memberid) {
var cursor = cursors[memberid];
return cursor ? stepsTranslator.convertDomPointToSteps(cursor.getNode(), 0) : 0;
};
/**
* This function returns the position and selection length in ODF world of
* the cursor of the member.
* position is always the number of steps from root node to the anchor node
* length is the number of steps from anchor node to focus node
* !IMPORTANT! length is a vector, and may be negative if the cursor selection
* is reversed (i.e., user clicked and dragged the cursor backwards)
* @param {!string} memberid
* @returns {{position: !number, length: !number}}
*/
this.getCursorSelection = function(memberid) {
var cursor = cursors[memberid],
focusPosition = 0,
anchorPosition = 0;
if (cursor) {
focusPosition = stepsTranslator.convertDomPointToSteps(cursor.getNode(), 0);
anchorPosition = stepsTranslator.convertDomPointToSteps(cursor.getAnchorNode(), 0);
}
return {
position: anchorPosition,
length: focusPosition - anchorPosition
};
};
/**
* @return {!core.PositionFilter}
*/
this.getPositionFilter = function () {
return filter;
};
/**
* @return {!odf.OdfCanvas}
*/
this.getOdfCanvas = function () {
return odfCanvas;
};
/**
* @return {!Element}
*/
this.getRootNode = getRootNode;
/**
* @param {!string} memberid
* @return {ops.OdtCursor}
*/
this.getCursor = function (memberid) {
return cursors[memberid];
};
/**
* @return {!Array.<!ops.OdtCursor>}
*/
this.getCursors = function () {
var list = [], i;
for (i in cursors) {
if (cursors.hasOwnProperty(i)) {
list.push(cursors[i]);
}
}
return list;
};
/**
* @param {!ops.OdtCursor} cursor
* @return {undefined}
*/
this.addCursor = function (cursor) {
runtime.assert(Boolean(cursor), "OdtDocument::addCursor without cursor");
var distanceToFirstTextNode = cursor.getStepCounter().countSteps(1, filter),
memberid = cursor.getMemberId();
runtime.assert(typeof memberid === "string", "OdtDocument::addCursor has cursor without memberid");
runtime.assert(!cursors[memberid], "OdtDocument::addCursor is adding a duplicate cursor with memberid " + memberid);
cursor.move(distanceToFirstTextNode);
cursors[memberid] = cursor;
};
/**
* @param {!string} memberid
* @return {!boolean}
*/
this.removeCursor = function (memberid) {
var cursor = cursors[memberid];
if (cursor) {
cursor.removeFromOdtDocument();
delete cursors[memberid];
self.emit(ops.OdtDocument.signalCursorRemoved, memberid);
return true;
}
return false;
};
/**
* @param {!string} metadataId
* @return {?string}
*/
this.getMetaData = function (metadataId) {
var node = odfCanvas.odfContainer().rootElement.firstChild;
while (node && node.localName !== "meta") {
node = node.nextSibling;
}
node = node && node.firstChild;
while (node && node.localName !== metadataId) {
node = node.nextSibling;
}
node = node && node.firstChild;
while (node && node.nodeType !== Node.TEXT_NODE) {
node = node.nextSibling;
}
return node ? node.data : null;
};
/**
* @return {!odf.Formatting}
*/
this.getFormatting = function () {
return odfCanvas.getFormatting();
};
/**
* @param {!string} eventid
* @param {*} args
* @return {undefined}
*/
this.emit = function (eventid, args) {
eventNotifier.emit(eventid, args);
};
/**
* @param {!string} eventid
* @param {!Function} cb
* @return {undefined}
*/
this.subscribe = function (eventid, cb) {
eventNotifier.subscribe(eventid, cb);
};
/**
* @param {!string} eventid
* @param {!Function} cb
* @return {undefined}
*/
this.unsubscribe = function (eventid, cb) {
eventNotifier.unsubscribe(eventid, cb);
};
/**
* @param {!string} inputMemberId
* @reurn {!RootFilter}
*/
this.createRootFilter = function (inputMemberId) {
return new RootFilter(inputMemberId);
};
/**
* @param {!function(!Object=)} callback, passing an error object in case of error
* @return {undefined}
*/
this.close = function(callback) {
// TODO: check if anything needs to be cleaned up
callback();
};
/**
* @param {!function(!Object=)} callback, passing an error object in case of error
* @return {undefined}
*/
this.destroy = function(callback) {
callback();
};
/**
* @return {undefined}
*/
function init() {
filter = new ops.TextPositionFilter(getRootNode);
odfUtils = new odf.OdfUtils();
domUtils = new core.DomUtils();
stepsTranslator = new ops.StepsTranslator(getRootNode, gui.SelectionMover.createPositionIterator, filter, 500);
eventNotifier.subscribe(ops.OdtDocument.signalStepsInserted, stepsTranslator.handleStepsInserted);
eventNotifier.subscribe(ops.OdtDocument.signalStepsRemoved, stepsTranslator.handleStepsRemoved);
}
init();
};
/**@const*/ops.OdtDocument.signalCursorAdded = "cursor/added";
/**@const*/ops.OdtDocument.signalCursorRemoved = "cursor/removed";
/**@const*/ops.OdtDocument.signalCursorMoved = "cursor/moved";
/**@const*/ops.OdtDocument.signalParagraphChanged = "paragraph/changed";
/**@const*/ops.OdtDocument.signalTableAdded = "table/added";
/**@const*/ops.OdtDocument.signalCommonStyleCreated = "style/created";
/**@const*/ops.OdtDocument.signalCommonStyleDeleted = "style/deleted";
/**@const*/ops.OdtDocument.signalParagraphStyleModified = "paragraphstyle/modified";
/**@const*/ops.OdtDocument.signalOperationExecuted = "operation/executed";
/**@const*/ops.OdtDocument.signalUndoStackChanged = "undo/changed";
/**@const*/ops.OdtDocument.signalStepsInserted = "steps/inserted";
/**@const*/ops.OdtDocument.signalStepsRemoved = "steps/removed";
(function () {
"use strict";
return ops.OdtDocument;
}());
// vim:expandtab