Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderTextControlSingleLine.cpp
1 /**
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).
6  *
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.
11  *
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.
16  *
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.
21  *
22  */
23
24 #include "config.h"
25 #include "core/rendering/RenderTextControlSingleLine.h"
26
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"
38
39 using namespace std;
40
41 namespace WebCore {
42
43 using namespace HTMLNames;
44
45 RenderTextControlSingleLine::RenderTextControlSingleLine(HTMLInputElement* element)
46     : RenderTextControl(element)
47     , m_shouldDrawCapsLockIndicator(false)
48     , m_desiredInnerTextLogicalHeight(-1)
49 {
50     ASSERT(element->hasTagName(inputTag));
51 }
52
53 RenderTextControlSingleLine::~RenderTextControlSingleLine()
54 {
55 }
56
57 inline Element* RenderTextControlSingleLine::containerElement() const
58 {
59     return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::textFieldContainer());
60 }
61
62 inline Element* RenderTextControlSingleLine::editingViewPortElement() const
63 {
64     return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::editingViewPort());
65 }
66
67 inline HTMLElement* RenderTextControlSingleLine::innerSpinButtonElement() const
68 {
69     return toHTMLElement(inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
70 }
71
72 void RenderTextControlSingleLine::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
73 {
74     RenderTextControl::paint(paintInfo, paintOffset);
75
76     if (paintInfo.phase == PaintPhaseBlockBackground && m_shouldDrawCapsLockIndicator) {
77         LayoutRect contentsRect = contentBoxRect();
78
79         // Center in the block progression direction.
80         if (isHorizontalWritingMode())
81             contentsRect.setY((height() - contentsRect.height()) / 2);
82         else
83             contentsRect.setX((width() - contentsRect.width()) / 2);
84
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));
88     }
89 }
90
91 LayoutUnit RenderTextControlSingleLine::computeLogicalHeightLimit() const
92 {
93     return containerElement() ? contentLogicalHeight() : logicalHeight();
94 }
95
96 void RenderTextControlSingleLine::layout()
97 {
98     LayoutRectRecorder recorder(*this);
99     SubtreeLayoutScope layoutScope(this);
100
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.
107
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.
111
112     RenderBox* innerTextRenderer = innerTextElement()->renderBox();
113     RenderBox* viewPortRenderer = editingViewPortElement() ? editingViewPortElement()->renderBox() : 0;
114
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);
119     }
120     if (viewPortRenderer && !viewPortRenderer->style()->logicalHeight().isAuto()) {
121         viewPortRenderer->style()->setLogicalHeight(Length(Auto));
122         layoutScope.setNeedsLayout(viewPortRenderer);
123     }
124
125     RenderBlockFlow::layoutBlock(false);
126
127     Element* container = containerElement();
128     RenderBox* containerRenderer = container ? container->renderBox() : 0;
129
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);
136
137         m_desiredInnerTextLogicalHeight = desiredLogicalHeight;
138
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);
144         }
145     }
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);
156         } else
157             containerRenderer->style()->setLogicalHeight(Length(containerLogicalHeight, Fixed));
158     }
159
160     // If we need another layout pass, we have changed one of children's height so we need to relayout them.
161     if (needsLayout())
162         RenderBlockFlow::layoutBlock(true);
163
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)));
168     } else
169         centerContainerIfNeeded(containerRenderer);
170
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()));
176         else
177             innerSpinBox->setLogicalLocation(LayoutPoint(parentBox->logicalWidth() - innerSpinBox->logicalWidth() + paddingLogicalRight(), -paddingBefore()));
178         innerSpinBox->setLogicalHeight(logicalHeight() - borderBefore() - borderAfter());
179     }
180
181     HTMLElement* placeholderElement = inputElement()->placeholderElement();
182     if (RenderBox* placeholderBox = placeholderElement ? placeholderElement->renderBox() : 0) {
183         LayoutSize innerTextSize;
184         LayoutRectRecorder placeholderBoxRecorder(*placeholderBox);
185
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);
201
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();
206         }
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.
209         if (neededLayout)
210             computeOverflow(clientLogicalBottom());
211     }
212 }
213
214 bool RenderTextControlSingleLine::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
215 {
216     if (!RenderTextControl::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, hitTestAction))
217         return false;
218
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());
231         }
232         hitInnerTextElement(result, pointInParent, accumulatedOffset);
233     }
234     return true;
235 }
236
237 void RenderTextControlSingleLine::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
238 {
239     m_desiredInnerTextLogicalHeight = -1;
240     RenderTextControl::styleDidChange(diff, oldStyle);
241
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());
248     }
249     Element* container = containerElement();
250     if (RenderObject* containerRenderer = container ? container->renderer() : 0) {
251         containerRenderer->style()->setHeight(Length());
252         containerRenderer->style()->setWidth(Length());
253     }
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);
260 }
261
262 void RenderTextControlSingleLine::capsLockStateMayHaveChanged()
263 {
264     if (!node())
265         return;
266
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;
273
274     if (Frame* frame = document().frame())
275         shouldDrawCapsLockIndicator = inputElement()->isPasswordField() && frame->selection().isFocusedAndActive() && document().focusedElement() == node() && PlatformKeyboardEvent::currentCapsLockState();
276
277     if (shouldDrawCapsLockIndicator != m_shouldDrawCapsLockIndicator) {
278         m_shouldDrawCapsLockIndicator = shouldDrawCapsLockIndicator;
279         repaint();
280     }
281 }
282
283 bool RenderTextControlSingleLine::hasControlClip() const
284 {
285     // Apply control clip for text fields with decorations.
286     return !!containerElement();
287 }
288
289 LayoutRect RenderTextControlSingleLine::controlClipRect(const LayoutPoint& additionalOffset) const
290 {
291     ASSERT(hasControlClip());
292     LayoutRect clipRect = contentBoxRect();
293     if (containerElement()->renderBox())
294         clipRect = unionRect(clipRect, containerElement()->renderBox()->frameRect());
295     clipRect.moveBy(additionalOffset);
296     return clipRect;
297 }
298
299 float RenderTextControlSingleLine::getAvgCharWidth(AtomicString family)
300 {
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);
307
308     return RenderTextControl::getAvgCharWidth(family);
309 }
310
311 LayoutUnit RenderTextControlSingleLine::preferredContentLogicalWidth(float charWidth) const
312 {
313     int factor;
314     bool includesDecoration = inputElement()->sizeShouldIncludeDecoration(factor);
315     if (factor <= 0)
316         factor = 20;
317
318     LayoutUnit result = LayoutUnit::fromFloatCeil(charWidth * factor);
319
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());
330
331     // For text inputs, IE adds some extra width.
332     if (maxCharWidth > 0.f)
333         result += maxCharWidth - charWidth;
334
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();
342         }
343     }
344
345     return result;
346 }
347
348 LayoutUnit RenderTextControlSingleLine::computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const
349 {
350     return lineHeight + nonContentHeight;
351 }
352
353 void RenderTextControlSingleLine::updateFromElement()
354 {
355     RenderTextControl::updateFromElement();
356 }
357
358 PassRefPtr<RenderStyle> RenderTextControlSingleLine::createInnerTextStyle(const RenderStyle* startStyle) const
359 {
360     RefPtr<RenderStyle> textBlockStyle = RenderStyle::create();
361     textBlockStyle->inheritFrom(startStyle);
362     adjustInnerTextStyle(textBlockStyle.get());
363
364     textBlockStyle->setWhiteSpace(PRE);
365     textBlockStyle->setOverflowWrap(NormalOverflowWrap);
366     textBlockStyle->setOverflowX(OHIDDEN);
367     textBlockStyle->setOverflowY(OHIDDEN);
368     textBlockStyle->setTextOverflow(textShouldBeTruncated() ? TextOverflowEllipsis : TextOverflowClip);
369
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());
375
376     textBlockStyle->setDisplay(BLOCK);
377     textBlockStyle->setUnique();
378
379     if (inputElement()->shouldRevealPassword())
380         textBlockStyle->setTextSecurity(TSNONE);
381
382     return textBlockStyle.release();
383 }
384
385 bool RenderTextControlSingleLine::textShouldBeTruncated() const
386 {
387     return document().focusedElement() != node() && style()->textOverflow() == TextOverflowEllipsis;
388 }
389
390 void RenderTextControlSingleLine::autoscroll(const IntPoint& position)
391 {
392     RenderBox* renderer = innerTextElement()->renderBox();
393     if (!renderer)
394         return;
395
396     renderer->autoscroll(position);
397 }
398
399 int RenderTextControlSingleLine::scrollWidth() const
400 {
401     if (innerTextElement())
402         return innerTextElement()->scrollWidth();
403     return RenderBlockFlow::scrollWidth();
404 }
405
406 int RenderTextControlSingleLine::scrollHeight() const
407 {
408     if (innerTextElement())
409         return innerTextElement()->scrollHeight();
410     return RenderBlockFlow::scrollHeight();
411 }
412
413 int RenderTextControlSingleLine::scrollLeft() const
414 {
415     if (innerTextElement())
416         return innerTextElement()->scrollLeft();
417     return RenderBlockFlow::scrollLeft();
418 }
419
420 int RenderTextControlSingleLine::scrollTop() const
421 {
422     if (innerTextElement())
423         return innerTextElement()->scrollTop();
424     return RenderBlockFlow::scrollTop();
425 }
426
427 void RenderTextControlSingleLine::setScrollLeft(int newLeft)
428 {
429     if (innerTextElement())
430         innerTextElement()->setScrollLeft(newLeft);
431 }
432
433 void RenderTextControlSingleLine::setScrollTop(int newTop)
434 {
435     if (innerTextElement())
436         innerTextElement()->setScrollTop(newTop);
437 }
438
439 HTMLInputElement* RenderTextControlSingleLine::inputElement() const
440 {
441     return toHTMLInputElement(node());
442 }
443
444 }