SurroundingText.cpp [plain text]
#include "config.h"
#include "SurroundingText.h"
#include "Document.h"
#include "Range.h"
#include "TextIterator.h"
#include "VisiblePosition.h"
#include "VisibleSelection.h"
#include "visible_units.h"
namespace WebCore {
SurroundingText::SurroundingText(const VisiblePosition& visiblePosition, unsigned maxLength)
: m_positionOffsetInContent(0)
{
const unsigned halfMaxLength = maxLength / 2;
CharacterIterator forwardIterator(makeRange(visiblePosition, endOfDocument(visiblePosition)).get(), TextIteratorStopsOnFormControls);
forwardIterator.advance(maxLength - halfMaxLength);
Position position = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
Document* document = position.document();
if (!Range::create(document, position, forwardIterator.range()->startPosition())->text().length())
return;
BackwardsCharacterIterator backwardsIterator(makeRange(startOfDocument(visiblePosition), visiblePosition).get(), TextIteratorStopsOnFormControls);
backwardsIterator.advance(halfMaxLength);
m_positionOffsetInContent = Range::create(document, backwardsIterator.range()->endPosition(), position)->text().length();
m_contentRange = Range::create(document, backwardsIterator.range()->endPosition(), forwardIterator.range()->startPosition());
}
PassRefPtr<Range> SurroundingText::rangeFromContentOffsets(unsigned startOffsetInContent, unsigned endOffsetInContent)
{
if (startOffsetInContent >= endOffsetInContent || endOffsetInContent > content().length())
return 0;
CharacterIterator iterator(m_contentRange.get());
iterator.advance(startOffsetInContent);
Position start = iterator.range()->startPosition();
iterator.advance(endOffsetInContent - startOffsetInContent);
Position end = iterator.range()->startPosition();
return Range::create(start.document(), start, end);
}
String SurroundingText::content() const
{
if (m_contentRange)
return m_contentRange->text();
return String();
}
unsigned SurroundingText::positionOffsetInContent() const
{
return m_positionOffsetInContent;
}
}