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