2 * Copyright (C) 2006, 2007, 2010 Apple Inc. All rights reserved.
3 * (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
4 * Copyright (C) 2010 Google Inc. All rights reserved.
5 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
25 #include "core/rendering/RenderTextControlSingleLine.h"
27 #include "CSSValueKeywords.h"
28 #include "core/dom/shadow/ShadowRoot.h"
29 #include "core/editing/FrameSelection.h"
30 #include "core/frame/LocalFrame.h"
31 #include "core/html/shadow/ShadowElementNames.h"
32 #include "core/rendering/HitTestResult.h"
33 #include "core/rendering/LayoutRectRecorder.h"
34 #include "core/rendering/RenderLayer.h"
35 #include "core/rendering/RenderTheme.h"
36 #include "platform/PlatformKeyboardEvent.h"
37 #include "platform/fonts/SimpleFontData.h"
43 using namespace HTMLNames;
45 RenderTextControlSingleLine::RenderTextControlSingleLine(HTMLInputElement* element)
46 : RenderTextControl(element)
47 , m_shouldDrawCapsLockIndicator(false)
48 , m_desiredInnerTextLogicalHeight(-1)
52 RenderTextControlSingleLine::~RenderTextControlSingleLine()
56 inline Element* RenderTextControlSingleLine::containerElement() const
58 return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::textFieldContainer());
61 inline Element* RenderTextControlSingleLine::editingViewPortElement() const
63 return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::editingViewPort());
66 inline HTMLElement* RenderTextControlSingleLine::innerSpinButtonElement() const
68 return toHTMLElement(inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
71 void RenderTextControlSingleLine::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
73 RenderTextControl::paint(paintInfo, paintOffset);
75 if (paintInfo.phase == PaintPhaseBlockBackground && m_shouldDrawCapsLockIndicator) {
76 LayoutRect contentsRect = contentBoxRect();
78 // Center in the block progression direction.
79 if (isHorizontalWritingMode())
80 contentsRect.setY((height() - contentsRect.height()) / 2);
82 contentsRect.setX((width() - contentsRect.width()) / 2);
84 // Convert the rect into the coords used for painting the content
85 contentsRect.moveBy(paintOffset + location());
86 RenderTheme::theme().paintCapsLockIndicator(this, paintInfo, pixelSnappedIntRect(contentsRect));
90 LayoutUnit RenderTextControlSingleLine::computeLogicalHeightLimit() const
92 return containerElement() ? contentLogicalHeight() : logicalHeight();
95 void RenderTextControlSingleLine::layout()
97 LayoutRectRecorder recorder(*this);
98 SubtreeLayoutScope layoutScope(this);
100 // FIXME: We should remove the height-related hacks in layout() and
101 // styleDidChange(). We need them because
102 // - Center the inner elements vertically if the input height is taller than
103 // the intrinsic height of the inner elements.
104 // - Shrink the inner elment heights if the input height is samller than the
105 // intrinsic heights of the inner elements.
107 // We don't honor paddings and borders for textfields without decorations
108 // and type=search if the text height is taller than the contentHeight()
109 // because of compability.
111 RenderBox* innerTextRenderer = innerTextElement()->renderBox();
112 RenderBox* viewPortRenderer = editingViewPortElement() ? editingViewPortElement()->renderBox() : 0;
114 // To ensure consistency between layouts, we need to reset any conditionally overriden height.
115 if (innerTextRenderer && !innerTextRenderer->style()->logicalHeight().isAuto()) {
116 innerTextRenderer->style()->setLogicalHeight(Length(Auto));
117 layoutScope.setNeedsLayout(innerTextRenderer);
119 if (viewPortRenderer && !viewPortRenderer->style()->logicalHeight().isAuto()) {
120 viewPortRenderer->style()->setLogicalHeight(Length(Auto));
121 layoutScope.setNeedsLayout(viewPortRenderer);
124 RenderBlockFlow::layoutBlock(false);
126 Element* container = containerElement();
127 RenderBox* containerRenderer = container ? container->renderBox() : 0;
129 // Set the text block height
130 LayoutUnit desiredLogicalHeight = textBlockLogicalHeight();
131 LayoutUnit logicalHeightLimit = computeLogicalHeightLimit();
132 if (innerTextRenderer && innerTextRenderer->logicalHeight() > logicalHeightLimit) {
133 if (desiredLogicalHeight != innerTextRenderer->logicalHeight())
134 layoutScope.setNeedsLayout(this);
136 m_desiredInnerTextLogicalHeight = desiredLogicalHeight;
138 innerTextRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
139 layoutScope.setNeedsLayout(innerTextRenderer);
140 if (viewPortRenderer) {
141 viewPortRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
142 layoutScope.setNeedsLayout(viewPortRenderer);
145 // The container might be taller because of decoration elements.
146 if (containerRenderer) {
147 containerRenderer->layoutIfNeeded();
148 LayoutUnit containerLogicalHeight = containerRenderer->logicalHeight();
149 if (containerLogicalHeight > logicalHeightLimit) {
150 containerRenderer->style()->setLogicalHeight(Length(logicalHeightLimit, Fixed));
151 layoutScope.setNeedsLayout(this);
152 } else if (containerRenderer->logicalHeight() < contentLogicalHeight()) {
153 containerRenderer->style()->setLogicalHeight(Length(contentLogicalHeight(), Fixed));
154 layoutScope.setNeedsLayout(this);
156 containerRenderer->style()->setLogicalHeight(Length(containerLogicalHeight, Fixed));
159 // If we need another layout pass, we have changed one of children's height so we need to relayout them.
161 RenderBlockFlow::layoutBlock(true);
163 // Center the child block in the block progression direction (vertical centering for horizontal text fields).
164 if (!container && innerTextRenderer && innerTextRenderer->height() != contentLogicalHeight()) {
165 LayoutUnit logicalHeightDiff = innerTextRenderer->logicalHeight() - contentLogicalHeight();
166 innerTextRenderer->setLogicalTop(innerTextRenderer->logicalTop() - (logicalHeightDiff / 2 + layoutMod(logicalHeightDiff, 2)));
168 centerContainerIfNeeded(containerRenderer);
170 // Ignores the paddings for the inner spin button.
171 if (RenderBox* innerSpinBox = innerSpinButtonElement() ? innerSpinButtonElement()->renderBox() : 0) {
172 RenderBox* parentBox = innerSpinBox->parentBox();
173 if (containerRenderer && !containerRenderer->style()->isLeftToRightDirection())
174 innerSpinBox->setLogicalLocation(LayoutPoint(-paddingLogicalLeft(), -paddingBefore()));
176 innerSpinBox->setLogicalLocation(LayoutPoint(parentBox->logicalWidth() - innerSpinBox->logicalWidth() + paddingLogicalRight(), -paddingBefore()));
177 innerSpinBox->setLogicalHeight(logicalHeight() - borderBefore() - borderAfter());
180 HTMLElement* placeholderElement = inputElement()->placeholderElement();
181 if (RenderBox* placeholderBox = placeholderElement ? placeholderElement->renderBox() : 0) {
182 LayoutSize innerTextSize;
183 LayoutRectRecorder placeholderBoxRecorder(*placeholderBox);
185 if (innerTextRenderer)
186 innerTextSize = innerTextRenderer->size();
187 placeholderBox->style()->setWidth(Length(innerTextSize.width() - placeholderBox->borderAndPaddingWidth(), Fixed));
188 placeholderBox->style()->setHeight(Length(innerTextSize.height() - placeholderBox->borderAndPaddingHeight(), Fixed));
189 bool neededLayout = placeholderBox->needsLayout();
190 bool placeholderBoxHadLayout = placeholderBox->everHadLayout();
191 placeholderBox->layoutIfNeeded();
192 LayoutPoint textOffset;
193 if (innerTextRenderer)
194 textOffset = innerTextRenderer->location();
195 if (editingViewPortElement() && editingViewPortElement()->renderBox())
196 textOffset += toLayoutSize(editingViewPortElement()->renderBox()->location());
197 if (containerRenderer)
198 textOffset += toLayoutSize(containerRenderer->location());
199 placeholderBox->setLocation(textOffset);
201 if (!placeholderBoxHadLayout && placeholderBox->checkForRepaintDuringLayout()) {
202 // This assumes a shadow tree without floats. If floats are added, the
203 // logic should be shared with RenderBlockFlow::layoutBlockChild.
204 placeholderBox->repaint();
206 // The placeholder gets layout last, after the parent text control and its other children,
207 // so in order to get the correct overflow from the placeholder we need to recompute it now.
209 computeOverflow(clientLogicalBottom());
213 bool RenderTextControlSingleLine::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
215 if (!RenderTextControl::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
218 // Say that we hit the inner text element if
219 // - we hit a node inside the inner text element,
220 // - we hit the <input> element (e.g. we're over the border or padding), or
221 // - we hit regions not in any decoration buttons.
222 Element* container = containerElement();
223 if (result.innerNode()->isDescendantOf(innerTextElement()) || result.innerNode() == node() || (container && container == result.innerNode())) {
224 LayoutPoint pointInParent = locationInContainer.point();
225 if (container && editingViewPortElement()) {
226 if (editingViewPortElement()->renderBox())
227 pointInParent -= toLayoutSize(editingViewPortElement()->renderBox()->location());
228 if (container->renderBox())
229 pointInParent -= toLayoutSize(container->renderBox()->location());
231 hitInnerTextElement(result, pointInParent, accumulatedOffset);
236 void RenderTextControlSingleLine::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
238 m_desiredInnerTextLogicalHeight = -1;
239 RenderTextControl::styleDidChange(diff, oldStyle);
241 // We may have set the width and the height in the old style in layout().
242 // Reset them now to avoid getting a spurious layout hint.
243 Element* viewPort = editingViewPortElement();
244 if (RenderObject* viewPortRenderer = viewPort ? viewPort->renderer() : 0) {
245 viewPortRenderer->style()->setHeight(Length());
246 viewPortRenderer->style()->setWidth(Length());
248 Element* container = containerElement();
249 if (RenderObject* containerRenderer = container ? container->renderer() : 0) {
250 containerRenderer->style()->setHeight(Length());
251 containerRenderer->style()->setWidth(Length());
253 RenderObject* innerTextRenderer = innerTextElement()->renderer();
254 if (innerTextRenderer && diff == StyleDifferenceLayout)
255 innerTextRenderer->setNeedsLayout();
256 if (HTMLElement* placeholder = inputElement()->placeholderElement())
257 placeholder->setInlineStyleProperty(CSSPropertyTextOverflow, textShouldBeTruncated() ? CSSValueEllipsis : CSSValueClip);
258 setHasOverflowClip(false);
261 void RenderTextControlSingleLine::capsLockStateMayHaveChanged()
266 // Only draw the caps lock indicator if these things are true:
267 // 1) The field is a password field
268 // 2) The frame is active
269 // 3) The element is focused
270 // 4) The caps lock is on
271 bool shouldDrawCapsLockIndicator = false;
273 if (LocalFrame* frame = document().frame())
274 shouldDrawCapsLockIndicator = inputElement()->isPasswordField() && frame->selection().isFocusedAndActive() && document().focusedElement() == node() && PlatformKeyboardEvent::currentCapsLockState();
276 if (shouldDrawCapsLockIndicator != m_shouldDrawCapsLockIndicator) {
277 m_shouldDrawCapsLockIndicator = shouldDrawCapsLockIndicator;
282 bool RenderTextControlSingleLine::hasControlClip() const
284 // Apply control clip for text fields with decorations.
285 return !!containerElement();
288 LayoutRect RenderTextControlSingleLine::controlClipRect(const LayoutPoint& additionalOffset) const
290 ASSERT(hasControlClip());
291 LayoutRect clipRect = contentBoxRect();
292 if (containerElement()->renderBox())
293 clipRect = unionRect(clipRect, containerElement()->renderBox()->frameRect());
294 clipRect.moveBy(additionalOffset);
298 float RenderTextControlSingleLine::getAvgCharWidth(AtomicString family)
300 // Since Lucida Grande is the default font, we want this to match the width
301 // of MS Shell Dlg, the default font for textareas in Firefox, Safari Win and
302 // IE for some encodings (in IE, the default font is encoding specific).
303 // 901 is the avgCharWidth value in the OS/2 table for MS Shell Dlg.
304 if (family == "Lucida Grande")
305 return scaleEmToUnits(901);
307 return RenderTextControl::getAvgCharWidth(family);
310 LayoutUnit RenderTextControlSingleLine::preferredContentLogicalWidth(float charWidth) const
313 bool includesDecoration = inputElement()->sizeShouldIncludeDecoration(factor);
317 LayoutUnit result = LayoutUnit::fromFloatCeil(charWidth * factor);
319 float maxCharWidth = 0.f;
320 AtomicString family = style()->font().fontDescription().family().family();
321 // Since Lucida Grande is the default font, we want this to match the width
322 // of MS Shell Dlg, the default font for textareas in Firefox, Safari Win and
323 // IE for some encodings (in IE, the default font is encoding specific).
324 // 4027 is the (xMax - xMin) value in the "head" font table for MS Shell Dlg.
325 if (family == "Lucida Grande")
326 maxCharWidth = scaleEmToUnits(4027);
327 else if (hasValidAvgCharWidth(family))
328 maxCharWidth = roundf(style()->font().primaryFont()->maxCharWidth());
330 // For text inputs, IE adds some extra width.
331 if (maxCharWidth > 0.f)
332 result += maxCharWidth - charWidth;
334 if (includesDecoration) {
335 HTMLElement* spinButton = innerSpinButtonElement();
336 if (RenderBox* spinRenderer = spinButton ? spinButton->renderBox() : 0) {
337 result += spinRenderer->borderAndPaddingLogicalWidth();
338 // Since the width of spinRenderer is not calculated yet, spinRenderer->logicalWidth() returns 0.
339 // So computedStyle()->logicalWidth() is used instead.
340 result += spinButton->computedStyle()->logicalWidth().value();
347 LayoutUnit RenderTextControlSingleLine::computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const
349 return lineHeight + nonContentHeight;
352 void RenderTextControlSingleLine::updateFromElement()
354 RenderTextControl::updateFromElement();
357 PassRefPtr<RenderStyle> RenderTextControlSingleLine::createInnerTextStyle(const RenderStyle* startStyle) const
359 RefPtr<RenderStyle> textBlockStyle = RenderStyle::create();
360 textBlockStyle->inheritFrom(startStyle);
361 adjustInnerTextStyle(textBlockStyle.get());
363 textBlockStyle->setWhiteSpace(PRE);
364 textBlockStyle->setOverflowWrap(NormalOverflowWrap);
365 textBlockStyle->setOverflowX(OHIDDEN);
366 textBlockStyle->setOverflowY(OHIDDEN);
367 textBlockStyle->setTextOverflow(textShouldBeTruncated() ? TextOverflowEllipsis : TextOverflowClip);
369 if (m_desiredInnerTextLogicalHeight >= 0)
370 textBlockStyle->setLogicalHeight(Length(m_desiredInnerTextLogicalHeight, Fixed));
371 // Do not allow line-height to be smaller than our default.
372 if (textBlockStyle->fontMetrics().lineSpacing() > lineHeight(true, HorizontalLine, PositionOfInteriorLineBoxes))
373 textBlockStyle->setLineHeight(RenderStyle::initialLineHeight());
375 textBlockStyle->setDisplay(BLOCK);
376 textBlockStyle->setUnique();
378 if (inputElement()->shouldRevealPassword())
379 textBlockStyle->setTextSecurity(TSNONE);
381 return textBlockStyle.release();
384 bool RenderTextControlSingleLine::textShouldBeTruncated() const
386 return document().focusedElement() != node() && style()->textOverflow() == TextOverflowEllipsis;
389 void RenderTextControlSingleLine::autoscroll(const IntPoint& position)
391 RenderBox* renderer = innerTextElement()->renderBox();
395 renderer->autoscroll(position);
398 int RenderTextControlSingleLine::scrollWidth() const
400 if (innerTextElement())
401 return innerTextElement()->scrollWidth();
402 return RenderBlockFlow::scrollWidth();
405 int RenderTextControlSingleLine::scrollHeight() const
407 if (innerTextElement())
408 return innerTextElement()->scrollHeight();
409 return RenderBlockFlow::scrollHeight();
412 int RenderTextControlSingleLine::scrollLeft() const
414 if (innerTextElement())
415 return innerTextElement()->scrollLeft();
416 return RenderBlockFlow::scrollLeft();
419 int RenderTextControlSingleLine::scrollTop() const
421 if (innerTextElement())
422 return innerTextElement()->scrollTop();
423 return RenderBlockFlow::scrollTop();
426 void RenderTextControlSingleLine::setScrollLeft(int newLeft)
428 if (innerTextElement())
429 innerTextElement()->setScrollLeft(newLeft);
432 void RenderTextControlSingleLine::setScrollTop(int newTop)
434 if (innerTextElement())
435 innerTextElement()->setScrollTop(newTop);
438 HTMLInputElement* RenderTextControlSingleLine::inputElement() const
440 return toHTMLInputElement(node());