Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderTextControl.cpp
1 /**
2  * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
3  *           (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  *
20  */
21
22 #include "config.h"
23 #include "core/rendering/RenderTextControl.h"
24
25 #include "core/html/HTMLTextFormControlElement.h"
26 #include "core/rendering/HitTestResult.h"
27 #include "core/rendering/RenderTheme.h"
28 #include "platform/scroll/ScrollbarTheme.h"
29 #include "wtf/unicode/CharacterNames.h"
30
31 using namespace std;
32
33 namespace WebCore {
34
35 RenderTextControl::RenderTextControl(HTMLTextFormControlElement* element)
36     : RenderBlockFlow(element)
37 {
38     ASSERT(element);
39 }
40
41 RenderTextControl::~RenderTextControl()
42 {
43 }
44
45 HTMLTextFormControlElement* RenderTextControl::textFormControlElement() const
46 {
47     return toHTMLTextFormControlElement(node());
48 }
49
50 HTMLElement* RenderTextControl::innerTextElement() const
51 {
52     return textFormControlElement()->innerTextElement();
53 }
54
55 void RenderTextControl::addChild(RenderObject* newChild, RenderObject* beforeChild)
56 {
57     // FIXME: This is a terrible hack to get the caret over the placeholder text since it'll
58     // make us paint the placeholder first. (See https://trac.webkit.org/changeset/118733)
59     Node* node = newChild->node();
60     if (node && node->isElementNode() && toElement(node)->shadowPseudoId() == "-webkit-input-placeholder")
61         RenderBlockFlow::addChild(newChild, firstChild());
62     else
63         RenderBlockFlow::addChild(newChild, beforeChild);
64 }
65
66 void RenderTextControl::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
67 {
68     RenderBlockFlow::styleDidChange(diff, oldStyle);
69     Element* innerText = innerTextElement();
70     if (!innerText)
71         return;
72     RenderBlock* innerTextRenderer = toRenderBlock(innerText->renderer());
73     if (innerTextRenderer) {
74         // We may have set the width and the height in the old style in layout().
75         // Reset them now to avoid getting a spurious layout hint.
76         innerTextRenderer->style()->setHeight(Length());
77         innerTextRenderer->style()->setWidth(Length());
78         innerTextRenderer->setStyle(createInnerTextStyle(style()));
79         innerText->setNeedsStyleRecalc(SubtreeStyleChange);
80     }
81     textFormControlElement()->updatePlaceholderVisibility(false);
82 }
83
84 static inline void updateUserModifyProperty(HTMLTextFormControlElement* node, RenderStyle* style)
85 {
86     style->setUserModify(node->isDisabledOrReadOnly() ? READ_ONLY : READ_WRITE_PLAINTEXT_ONLY);
87 }
88
89 void RenderTextControl::adjustInnerTextStyle(RenderStyle* textBlockStyle) const
90 {
91     // The inner block, if present, always has its direction set to LTR,
92     // so we need to inherit the direction and unicode-bidi style from the element.
93     textBlockStyle->setDirection(style()->direction());
94     textBlockStyle->setUnicodeBidi(style()->unicodeBidi());
95
96     updateUserModifyProperty(textFormControlElement(), textBlockStyle);
97 }
98
99 int RenderTextControl::textBlockLogicalHeight() const
100 {
101     return logicalHeight() - borderAndPaddingLogicalHeight();
102 }
103
104 int RenderTextControl::textBlockLogicalWidth() const
105 {
106     Element* innerText = innerTextElement();
107     ASSERT(innerText);
108
109     LayoutUnit unitWidth = logicalWidth() - borderAndPaddingLogicalWidth();
110     if (innerText->renderer())
111         unitWidth -= innerText->renderBox()->paddingStart() + innerText->renderBox()->paddingEnd();
112
113     return unitWidth;
114 }
115
116 void RenderTextControl::updateFromElement()
117 {
118     Element* innerText = innerTextElement();
119     if (innerText && innerText->renderer())
120         updateUserModifyProperty(textFormControlElement(), innerText->renderer()->style());
121 }
122
123 int RenderTextControl::scrollbarThickness() const
124 {
125     // FIXME: We should get the size of the scrollbar from the RenderTheme instead.
126     return ScrollbarTheme::theme()->scrollbarThickness();
127 }
128
129 void RenderTextControl::computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
130 {
131     HTMLElement* innerText = innerTextElement();
132     ASSERT(innerText);
133     if (RenderBox* innerTextBox = innerText->renderBox()) {
134         LayoutUnit nonContentHeight = innerTextBox->borderAndPaddingHeight() + innerTextBox->marginHeight();
135         logicalHeight = computeControlLogicalHeight(innerTextBox->lineHeight(true, HorizontalLine, PositionOfInteriorLineBoxes), nonContentHeight);
136
137         // We are able to have a horizontal scrollbar if the overflow style is scroll, or if its auto and there's no word wrap.
138         if ((isHorizontalWritingMode() && (style()->overflowX() == OSCROLL ||  (style()->overflowX() == OAUTO && innerText->renderer()->style()->overflowWrap() == NormalOverflowWrap)))
139             || (!isHorizontalWritingMode() && (style()->overflowY() == OSCROLL ||  (style()->overflowY() == OAUTO && innerText->renderer()->style()->overflowWrap() == NormalOverflowWrap))))
140             logicalHeight += scrollbarThickness();
141
142         // FIXME: The logical height of the inner text box should have been added before calling computeLogicalHeight to
143         // avoid this hack.
144         updateIntrinsicContentLogicalHeight(logicalHeight);
145
146         logicalHeight += borderAndPaddingHeight();
147     }
148
149     RenderBox::computeLogicalHeight(logicalHeight, logicalTop, computedValues);
150 }
151
152 void RenderTextControl::hitInnerTextElement(HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset)
153 {
154     HTMLElement* innerText = innerTextElement();
155     if (!innerText->renderer())
156         return;
157
158     LayoutPoint adjustedLocation = accumulatedOffset + location();
159     LayoutPoint localPoint = pointInContainer - toLayoutSize(adjustedLocation + innerText->renderBox()->location());
160     if (hasOverflowClip())
161         localPoint += scrolledContentOffset();
162     result.setInnerNode(innerText);
163     result.setInnerNonSharedNode(innerText);
164     result.setLocalPoint(localPoint);
165 }
166
167 static const char* const fontFamiliesWithInvalidCharWidth[] = {
168     "American Typewriter",
169     "Arial Hebrew",
170     "Chalkboard",
171     "Cochin",
172     "Corsiva Hebrew",
173     "Courier",
174     "Euphemia UCAS",
175     "Geneva",
176     "Gill Sans",
177     "Hei",
178     "Helvetica",
179     "Hoefler Text",
180     "InaiMathi",
181     "Kai",
182     "Lucida Grande",
183     "Marker Felt",
184     "Monaco",
185     "Mshtakan",
186     "New Peninim MT",
187     "Osaka",
188     "Raanana",
189     "STHeiti",
190     "Symbol",
191     "Times",
192     "Apple Braille",
193     "Apple LiGothic",
194     "Apple LiSung",
195     "Apple Symbols",
196     "AppleGothic",
197     "AppleMyungjo",
198     "#GungSeo",
199     "#HeadLineA",
200     "#PCMyungjo",
201     "#PilGi",
202 };
203
204 // For font families where any of the fonts don't have a valid entry in the OS/2 table
205 // for avgCharWidth, fallback to the legacy webkit behavior of getting the avgCharWidth
206 // from the width of a '0'. This only seems to apply to a fixed number of Mac fonts,
207 // but, in order to get similar rendering across platforms, we do this check for
208 // all platforms.
209 bool RenderTextControl::hasValidAvgCharWidth(AtomicString family)
210 {
211     static HashSet<AtomicString>* fontFamiliesWithInvalidCharWidthMap = 0;
212
213     if (family.isEmpty())
214         return false;
215
216     if (!fontFamiliesWithInvalidCharWidthMap) {
217         fontFamiliesWithInvalidCharWidthMap = new HashSet<AtomicString>;
218
219         for (size_t i = 0; i < WTF_ARRAY_LENGTH(fontFamiliesWithInvalidCharWidth); ++i)
220             fontFamiliesWithInvalidCharWidthMap->add(AtomicString(fontFamiliesWithInvalidCharWidth[i]));
221     }
222
223     return !fontFamiliesWithInvalidCharWidthMap->contains(family);
224 }
225
226 float RenderTextControl::getAvgCharWidth(AtomicString family)
227 {
228     if (hasValidAvgCharWidth(family))
229         return roundf(style()->font().primaryFont()->avgCharWidth());
230
231     const UChar ch = '0';
232     const String str = String(&ch, 1);
233     const Font& font = style()->font();
234     TextRun textRun = constructTextRun(this, font, str, style(), TextRun::AllowTrailingExpansion);
235     textRun.disableRoundingHacks();
236     return font.width(textRun);
237 }
238
239 float RenderTextControl::scaleEmToUnits(int x) const
240 {
241     // This matches the unitsPerEm value for MS Shell Dlg and Courier New from the "head" font table.
242     float unitsPerEm = 2048.0f;
243     return roundf(style()->font().fontDescription().computedSize() * x / unitsPerEm);
244 }
245
246 void RenderTextControl::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
247 {
248     // Use average character width. Matches IE.
249     AtomicString family = style()->font().fontDescription().family().family();
250     maxLogicalWidth = preferredContentLogicalWidth(const_cast<RenderTextControl*>(this)->getAvgCharWidth(family));
251     if (RenderBox* innerTextRenderBox = innerTextElement()->renderBox())
252         maxLogicalWidth += innerTextRenderBox->paddingStart() + innerTextRenderBox->paddingEnd();
253     if (!style()->logicalWidth().isPercent())
254         minLogicalWidth = maxLogicalWidth;
255 }
256
257 void RenderTextControl::computePreferredLogicalWidths()
258 {
259     ASSERT(preferredLogicalWidthsDirty());
260
261     m_minPreferredLogicalWidth = 0;
262     m_maxPreferredLogicalWidth = 0;
263
264     if (style()->logicalWidth().isFixed() && style()->logicalWidth().value() >= 0)
265         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = adjustContentBoxLogicalWidthForBoxSizing(style()->logicalWidth().value());
266     else
267         computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
268
269     if (style()->logicalMinWidth().isFixed() && style()->logicalMinWidth().value() > 0) {
270         m_maxPreferredLogicalWidth = max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(style()->logicalMinWidth().value()));
271         m_minPreferredLogicalWidth = max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(style()->logicalMinWidth().value()));
272     }
273
274     if (style()->logicalMaxWidth().isFixed()) {
275         m_maxPreferredLogicalWidth = min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(style()->logicalMaxWidth().value()));
276         m_minPreferredLogicalWidth = min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(style()->logicalMaxWidth().value()));
277     }
278
279     LayoutUnit toAdd = borderAndPaddingLogicalWidth();
280
281     m_minPreferredLogicalWidth += toAdd;
282     m_maxPreferredLogicalWidth += toAdd;
283
284     clearPreferredLogicalWidthsDirty();
285 }
286
287 void RenderTextControl::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
288 {
289     if (!size().isEmpty())
290         rects.append(pixelSnappedIntRect(additionalOffset, size()));
291 }
292
293 RenderObject* RenderTextControl::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
294 {
295     HTMLElement* placeholder = toHTMLTextFormControlElement(node())->placeholderElement();
296     RenderObject* placeholderRenderer = placeholder ? placeholder->renderer() : 0;
297     if (!placeholderRenderer)
298         return 0;
299     if (relayoutChildren)
300         layoutScope.setChildNeedsLayout(placeholderRenderer);
301     return placeholderRenderer;
302 }
303
304 } // namespace WebCore