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/html/shadow/ShadowElementNames.h"
31 #include "core/frame/Frame.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)
50 ASSERT(element->hasTagName(inputTag));
53 RenderTextControlSingleLine::~RenderTextControlSingleLine()
57 inline Element* RenderTextControlSingleLine::containerElement() const
59 return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::textFieldContainer());
62 inline Element* RenderTextControlSingleLine::editingViewPortElement() const
64 return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::editingViewPort());
67 inline HTMLElement* RenderTextControlSingleLine::innerSpinButtonElement() const
69 return toHTMLElement(inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
72 void RenderTextControlSingleLine::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
74 RenderTextControl::paint(paintInfo, paintOffset);
76 if (paintInfo.phase == PaintPhaseBlockBackground && m_shouldDrawCapsLockIndicator) {
77 LayoutRect contentsRect = contentBoxRect();
79 // Center in the block progression direction.
80 if (isHorizontalWritingMode())
81 contentsRect.setY((height() - contentsRect.height()) / 2);
83 contentsRect.setX((width() - contentsRect.width()) / 2);
85 // Convert the rect into the coords used for painting the content
86 contentsRect.moveBy(paintOffset + location());
87 RenderTheme::theme().paintCapsLockIndicator(this, paintInfo, pixelSnappedIntRect(contentsRect));
91 LayoutUnit RenderTextControlSingleLine::computeLogicalHeightLimit() const
93 return containerElement() ? contentLogicalHeight() : logicalHeight();
96 void RenderTextControlSingleLine::layout()
98 LayoutRectRecorder recorder(*this);
99 SubtreeLayoutScope layoutScope(this);
101 // FIXME: We should remove the height-related hacks in layout() and
102 // styleDidChange(). We need them because
103 // - Center the inner elements vertically if the input height is taller than
104 // the intrinsic height of the inner elements.
105 // - Shrink the inner elment heights if the input height is samller than the
106 // intrinsic heights of the inner elements.
108 // We don't honor paddings and borders for textfields without decorations
109 // and type=search if the text height is taller than the contentHeight()
110 // because of compability.
112 RenderBox* innerTextRenderer = innerTextElement()->renderBox();
113 RenderBox* viewPortRenderer = editingViewPortElement() ? editingViewPortElement()->renderBox() : 0;
115 // To ensure consistency between layouts, we need to reset any conditionally overriden height.
116 if (innerTextRenderer && !innerTextRenderer->style()->logicalHeight().isAuto()) {
117 innerTextRenderer->style()->setLogicalHeight(Length(Auto));
118 layoutScope.setNeedsLayout(innerTextRenderer);
120 if (viewPortRenderer && !viewPortRenderer->style()->logicalHeight().isAuto()) {
121 viewPortRenderer->style()->setLogicalHeight(Length(Auto));
122 layoutScope.setNeedsLayout(viewPortRenderer);
125 RenderBlockFlow::layoutBlock(false);
127 Element* container = containerElement();
128 RenderBox* containerRenderer = container ? container->renderBox() : 0;
130 // Set the text block height
131 LayoutUnit desiredLogicalHeight = textBlockLogicalHeight();
132 LayoutUnit logicalHeightLimit = computeLogicalHeightLimit();
133 if (innerTextRenderer && innerTextRenderer->logicalHeight() > logicalHeightLimit) {
134 if (desiredLogicalHeight != innerTextRenderer->logicalHeight())
135 layoutScope.setNeedsLayout(this);
137 m_desiredInnerTextLogicalHeight = desiredLogicalHeight;
139 innerTextRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
140 layoutScope.setNeedsLayout(innerTextRenderer);
141 if (viewPortRenderer) {
142 viewPortRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
143 layoutScope.setNeedsLayout(viewPortRenderer);
146 // The container might be taller because of decoration elements.
147 if (containerRenderer) {
148 containerRenderer->layoutIfNeeded();
149 LayoutUnit containerLogicalHeight = containerRenderer->logicalHeight();
150 if (containerLogicalHeight > logicalHeightLimit) {
151 containerRenderer->style()->setLogicalHeight(Length(logicalHeightLimit, Fixed));
152 layoutScope.setNeedsLayout(this);
153 } else if (containerRenderer->logicalHeight() < contentLogicalHeight()) {
154 containerRenderer->style()->setLogicalHeight(Length(contentLogicalHeight(), Fixed));
155 layoutScope.setNeedsLayout(this);
157 containerRenderer->style()->setLogicalHeight(Length(containerLogicalHeight, Fixed));
160 // If we need another layout pass, we have changed one of children's height so we need to relayout them.
162 RenderBlockFlow::layoutBlock(true);
164 // Center the child block in the block progression direction (vertical centering for horizontal text fields).
165 if (!container && innerTextRenderer && innerTextRenderer->height() != contentLogicalHeight()) {
166 LayoutUnit logicalHeightDiff = innerTextRenderer->logicalHeight() - contentLogicalHeight();
167 innerTextRenderer->setLogicalTop(innerTextRenderer->logicalTop() - (logicalHeightDiff / 2 + layoutMod(logicalHeightDiff, 2)));
169 centerContainerIfNeeded(containerRenderer);
171 // Ignores the paddings for the inner spin button.
172 if (RenderBox* innerSpinBox = innerSpinButtonElement() ? innerSpinButtonElement()->renderBox() : 0) {
173 RenderBox* parentBox = innerSpinBox->parentBox();
174 if (containerRenderer && !containerRenderer->style()->isLeftToRightDirection())
175 innerSpinBox->setLogicalLocation(LayoutPoint(-paddingLogicalLeft(), -paddingBefore()));
177 innerSpinBox->setLogicalLocation(LayoutPoint(parentBox->logicalWidth() - innerSpinBox->logicalWidth() + paddingLogicalRight(), -paddingBefore()));
178 innerSpinBox->setLogicalHeight(logicalHeight() - borderBefore() - borderAfter());
181 HTMLElement* placeholderElement = inputElement()->placeholderElement();
182 if (RenderBox* placeholderBox = placeholderElement ? placeholderElement->renderBox() : 0) {
183 LayoutSize innerTextSize;
184 LayoutRectRecorder placeholderBoxRecorder(*placeholderBox);
186 if (innerTextRenderer)
187 innerTextSize = innerTextRenderer->size();
188 placeholderBox->style()->setWidth(Length(innerTextSize.width() - placeholderBox->borderAndPaddingWidth(), Fixed));
189 placeholderBox->style()->setHeight(Length(innerTextSize.height() - placeholderBox->borderAndPaddingHeight(), Fixed));
190 bool neededLayout = placeholderBox->needsLayout();
191 bool placeholderBoxHadLayout = placeholderBox->everHadLayout();
192 placeholderBox->layoutIfNeeded();
193 LayoutPoint textOffset;
194 if (innerTextRenderer)
195 textOffset = innerTextRenderer->location();
196 if (editingViewPortElement() && editingViewPortElement()->renderBox())
197 textOffset += toLayoutSize(editingViewPortElement()->renderBox()->location());
198 if (containerRenderer)
199 textOffset += toLayoutSize(containerRenderer->location());
200 placeholderBox->setLocation(textOffset);
202 if (!placeholderBoxHadLayout && placeholderBox->checkForRepaintDuringLayout()) {
203 // This assumes a shadow tree without floats. If floats are added, the
204 // logic should be shared with RenderBlockFlow::layoutBlockChild.
205 placeholderBox->repaint();
207 // The placeholder gets layout last, after the parent text control and its other children,
208 // so in order to get the correct overflow from the placeholder we need to recompute it now.
210 computeOverflow(clientLogicalBottom());
214 bool RenderTextControlSingleLine::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
216 if (!RenderTextControl::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
219 // Say that we hit the inner text element if
220 // - we hit a node inside the inner text element,
221 // - we hit the <input> element (e.g. we're over the border or padding), or
222 // - we hit regions not in any decoration buttons.
223 Element* container = containerElement();
224 if (result.innerNode()->isDescendantOf(innerTextElement()) || result.innerNode() == node() || (container && container == result.innerNode())) {
225 LayoutPoint pointInParent = locationInContainer.point();
226 if (container && editingViewPortElement()) {
227 if (editingViewPortElement()->renderBox())
228 pointInParent -= toLayoutSize(editingViewPortElement()->renderBox()->location());
229 if (container->renderBox())
230 pointInParent -= toLayoutSize(container->renderBox()->location());
232 hitInnerTextElement(result, pointInParent, accumulatedOffset);
237 void RenderTextControlSingleLine::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
239 m_desiredInnerTextLogicalHeight = -1;
240 RenderTextControl::styleDidChange(diff, oldStyle);
242 // We may have set the width and the height in the old style in layout().
243 // Reset them now to avoid getting a spurious layout hint.
244 Element* viewPort = editingViewPortElement();
245 if (RenderObject* viewPortRenderer = viewPort ? viewPort->renderer() : 0) {
246 viewPortRenderer->style()->setHeight(Length());
247 viewPortRenderer->style()->setWidth(Length());
249 Element* container = containerElement();
250 if (RenderObject* containerRenderer = container ? container->renderer() : 0) {
251 containerRenderer->style()->setHeight(Length());
252 containerRenderer->style()->setWidth(Length());
254 RenderObject* innerTextRenderer = innerTextElement()->renderer();
255 if (innerTextRenderer && diff == StyleDifferenceLayout)
256 innerTextRenderer->setNeedsLayout();
257 if (HTMLElement* placeholder = inputElement()->placeholderElement())
258 placeholder->setInlineStyleProperty(CSSPropertyTextOverflow, textShouldBeTruncated() ? CSSValueEllipsis : CSSValueClip);
259 setHasOverflowClip(false);
262 void RenderTextControlSingleLine::capsLockStateMayHaveChanged()
267 // Only draw the caps lock indicator if these things are true:
268 // 1) The field is a password field
269 // 2) The frame is active
270 // 3) The element is focused
271 // 4) The caps lock is on
272 bool shouldDrawCapsLockIndicator = false;
274 if (Frame* frame = document().frame())
275 shouldDrawCapsLockIndicator = inputElement()->isPasswordField() && frame->selection().isFocusedAndActive() && document().focusedElement() == node() && PlatformKeyboardEvent::currentCapsLockState();
277 if (shouldDrawCapsLockIndicator != m_shouldDrawCapsLockIndicator) {
278 m_shouldDrawCapsLockIndicator = shouldDrawCapsLockIndicator;
283 bool RenderTextControlSingleLine::hasControlClip() const
285 // Apply control clip for text fields with decorations.
286 return !!containerElement();
289 LayoutRect RenderTextControlSingleLine::controlClipRect(const LayoutPoint& additionalOffset) const
291 ASSERT(hasControlClip());
292 LayoutRect clipRect = contentBoxRect();
293 if (containerElement()->renderBox())
294 clipRect = unionRect(clipRect, containerElement()->renderBox()->frameRect());
295 clipRect.moveBy(additionalOffset);
299 float RenderTextControlSingleLine::getAvgCharWidth(AtomicString family)
301 // Since Lucida Grande is the default font, we want this to match the width
302 // of MS Shell Dlg, the default font for textareas in Firefox, Safari Win and
303 // IE for some encodings (in IE, the default font is encoding specific).
304 // 901 is the avgCharWidth value in the OS/2 table for MS Shell Dlg.
305 if (family == "Lucida Grande")
306 return scaleEmToUnits(901);
308 return RenderTextControl::getAvgCharWidth(family);
311 LayoutUnit RenderTextControlSingleLine::preferredContentLogicalWidth(float charWidth) const
314 bool includesDecoration = inputElement()->sizeShouldIncludeDecoration(factor);
318 LayoutUnit result = LayoutUnit::fromFloatCeil(charWidth * factor);
320 float maxCharWidth = 0.f;
321 AtomicString family = style()->font().fontDescription().family().family();
322 // Since Lucida Grande is the default font, we want this to match the width
323 // of MS Shell Dlg, the default font for textareas in Firefox, Safari Win and
324 // IE for some encodings (in IE, the default font is encoding specific).
325 // 4027 is the (xMax - xMin) value in the "head" font table for MS Shell Dlg.
326 if (family == "Lucida Grande")
327 maxCharWidth = scaleEmToUnits(4027);
328 else if (hasValidAvgCharWidth(family))
329 maxCharWidth = roundf(style()->font().primaryFont()->maxCharWidth());
331 // For text inputs, IE adds some extra width.
332 if (maxCharWidth > 0.f)
333 result += maxCharWidth - charWidth;
335 if (includesDecoration) {
336 HTMLElement* spinButton = innerSpinButtonElement();
337 if (RenderBox* spinRenderer = spinButton ? spinButton->renderBox() : 0) {
338 result += spinRenderer->borderAndPaddingLogicalWidth();
339 // Since the width of spinRenderer is not calculated yet, spinRenderer->logicalWidth() returns 0.
340 // So computedStyle()->logicalWidth() is used instead.
341 result += spinButton->computedStyle()->logicalWidth().value();
348 LayoutUnit RenderTextControlSingleLine::computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const
350 return lineHeight + nonContentHeight;
353 void RenderTextControlSingleLine::updateFromElement()
355 RenderTextControl::updateFromElement();
358 PassRefPtr<RenderStyle> RenderTextControlSingleLine::createInnerTextStyle(const RenderStyle* startStyle) const
360 RefPtr<RenderStyle> textBlockStyle = RenderStyle::create();
361 textBlockStyle->inheritFrom(startStyle);
362 adjustInnerTextStyle(textBlockStyle.get());
364 textBlockStyle->setWhiteSpace(PRE);
365 textBlockStyle->setOverflowWrap(NormalOverflowWrap);
366 textBlockStyle->setOverflowX(OHIDDEN);
367 textBlockStyle->setOverflowY(OHIDDEN);
368 textBlockStyle->setTextOverflow(textShouldBeTruncated() ? TextOverflowEllipsis : TextOverflowClip);
370 if (m_desiredInnerTextLogicalHeight >= 0)
371 textBlockStyle->setLogicalHeight(Length(m_desiredInnerTextLogicalHeight, Fixed));
372 // Do not allow line-height to be smaller than our default.
373 if (textBlockStyle->fontMetrics().lineSpacing() > lineHeight(true, HorizontalLine, PositionOfInteriorLineBoxes))
374 textBlockStyle->setLineHeight(RenderStyle::initialLineHeight());
376 textBlockStyle->setDisplay(BLOCK);
377 textBlockStyle->setUnique();
379 if (inputElement()->shouldRevealPassword())
380 textBlockStyle->setTextSecurity(TSNONE);
382 return textBlockStyle.release();
385 bool RenderTextControlSingleLine::textShouldBeTruncated() const
387 return document().focusedElement() != node() && style()->textOverflow() == TextOverflowEllipsis;
390 void RenderTextControlSingleLine::autoscroll(const IntPoint& position)
392 RenderBox* renderer = innerTextElement()->renderBox();
396 renderer->autoscroll(position);
399 int RenderTextControlSingleLine::scrollWidth() const
401 if (innerTextElement())
402 return innerTextElement()->scrollWidth();
403 return RenderBlockFlow::scrollWidth();
406 int RenderTextControlSingleLine::scrollHeight() const
408 if (innerTextElement())
409 return innerTextElement()->scrollHeight();
410 return RenderBlockFlow::scrollHeight();
413 int RenderTextControlSingleLine::scrollLeft() const
415 if (innerTextElement())
416 return innerTextElement()->scrollLeft();
417 return RenderBlockFlow::scrollLeft();
420 int RenderTextControlSingleLine::scrollTop() const
422 if (innerTextElement())
423 return innerTextElement()->scrollTop();
424 return RenderBlockFlow::scrollTop();
427 void RenderTextControlSingleLine::setScrollLeft(int newLeft)
429 if (innerTextElement())
430 innerTextElement()->setScrollLeft(newLeft);
433 void RenderTextControlSingleLine::setScrollTop(int newTop)
435 if (innerTextElement())
436 innerTextElement()->setScrollTop(newTop);
439 HTMLInputElement* RenderTextControlSingleLine::inputElement() const
441 return toHTMLInputElement(node());