File: RenderFileUploadControl.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (352 lines) | stat: -rw-r--r-- 14,641 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
 * Copyright (C) 2006, 2007, 2012 Apple Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#include "config.h"
#include "RenderFileUploadControl.h"

#include "ElementRareData.h"
#include "FileList.h"
#include "FontCascade.h"
#include "GraphicsContext.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "Icon.h"
#include "InlineIteratorInlineBox.h"
#include "LocalizedStrings.h"
#include "PaintInfo.h"
#include "RenderBlockInlines.h"
#include "RenderBoxInlines.h"
#include "RenderBoxModelObjectInlines.h"
#include "RenderButton.h"
#include "RenderElementInlines.h"
#include "RenderText.h"
#include "RenderTheme.h"
#include "ShadowRoot.h"
#include "StringTruncator.h"
#include "TextRun.h"
#include "VisiblePosition.h"
#include <math.h>
#include <wtf/TZoneMallocInlines.h>

namespace WebCore {

using namespace HTMLNames;

WTF_MAKE_TZONE_OR_ISO_ALLOCATED_IMPL(RenderFileUploadControl);

constexpr int afterButtonSpacing = 4;
constexpr int buttonShadowHeight = 2;

#if !PLATFORM(COCOA)
// On Cocoa platforms the icon height matches the button height, to maximize the icon size.
constexpr int iconLogicalHeight = 16;
constexpr int iconLogicalWidth = 16;
#endif

#if !PLATFORM(IOS_FAMILY)
constexpr int iconFilenameSpacing = 2;
constexpr int defaultWidthNumChars = 34;
#else
constexpr int iconFilenameSpacing = afterButtonSpacing;
constexpr int defaultWidthNumChars = 38;
#endif

RenderFileUploadControl::RenderFileUploadControl(HTMLInputElement& input, RenderStyle&& style)
    : RenderBlockFlow(Type::FileUploadControl, input, WTFMove(style))
    , m_canReceiveDroppedFiles(input.canReceiveDroppedFiles())
{
    ASSERT(isRenderFileUploadControl());
}

RenderFileUploadControl::~RenderFileUploadControl() = default;

HTMLInputElement& RenderFileUploadControl::inputElement() const
{
    return downcast<HTMLInputElement>(nodeForNonAnonymous());
}

void RenderFileUploadControl::updateFromElement()
{
    ASSERT(inputElement().isFileUpload());

    if (HTMLInputElement* button = uploadButton()) {
        bool newCanReceiveDroppedFilesState = inputElement().canReceiveDroppedFiles();
        if (m_canReceiveDroppedFiles != newCanReceiveDroppedFilesState) {
            m_canReceiveDroppedFiles = newCanReceiveDroppedFilesState;
            button->setActive(newCanReceiveDroppedFilesState);
        }
    }

    // This only supports clearing out the files, but that's OK because for
    // security reasons that's the only change the DOM is allowed to make.
    FileList* files = inputElement().files();
    ASSERT(files);
    if (files && files->isEmpty())
        repaint();
}

static int nodeLogicalWidth(Node* node)
{
    return (node && node->renderBox()) ? roundToInt(node->renderBox()->logicalSize().width()) : 0;
}

#if PLATFORM(COCOA)
static int nodeLogicalHeight(Node* node)
{
    return (node && node->renderBox()) ? roundToInt(node->renderBox()->logicalSize().height()) : 0;
}
#endif

int RenderFileUploadControl::maxFilenameLogicalWidth() const
{
#if PLATFORM(COCOA)
    int iconLogicalWidth = nodeLogicalHeight(uploadButton());
#endif
    return std::max(0, roundToInt(contentBoxLogicalWidth()) - nodeLogicalWidth(uploadButton()) - afterButtonSpacing
        - (inputElement().icon() ? iconLogicalWidth + iconFilenameSpacing : 0));
}

void RenderFileUploadControl::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
    if (style().usedVisibility() != Visibility::Visible)
        return;
    
    if (!paintInfo.context().paintingDisabled())
        paintControl(paintInfo, paintOffset);

    // Paint the children.
    RenderBlockFlow::paintObject(paintInfo, paintOffset);
}

void RenderFileUploadControl::paintControl(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
    // Push a clip.
    GraphicsContextStateSaver stateSaver(paintInfo.context(), false);
    if (paintInfo.phase == PaintPhase::Foreground || paintInfo.phase == PaintPhase::ChildBlockBackgrounds) {
        IntRect clipRect = enclosingIntRect(LayoutRect(paintOffset.x() + borderLeft(), paintOffset.y() + borderTop(),
                         width() - borderLeft() - borderRight(), height() - borderBottom() - borderTop() + buttonShadowHeight));
        if (clipRect.isEmpty())
            return;
        stateSaver.save();
        paintInfo.context().clip(clipRect);
    }

    auto isHorizontalWritingMode = writingMode().isHorizontal();
    auto isBlockFlipped = writingMode().isBlockFlipped();
    auto logicalPaintOffset = isHorizontalWritingMode ? paintOffset : paintOffset.transposedPoint();

    if (paintInfo.phase == PaintPhase::Foreground) {
        const String& displayedFilename = fileTextValue();
        const FontCascade& font = style().fontCascade();
        TextRun textRun = constructTextRun(displayedFilename, style(), ExpansionBehavior::allowRightOnly(), RespectDirection | RespectDirectionOverride);
#if PLATFORM(COCOA)
        int iconLogicalHeight = nodeLogicalHeight(uploadButton());
        int iconLogicalWidth = iconLogicalHeight;
#endif
        // Determine where the filename should be placed
        LayoutUnit contentLogicalLeft = logicalPaintOffset.x() + logicalLeftOffsetForContent();
        if (writingMode().isLogicalLeftInlineStart())
            contentLogicalLeft += textIndentOffset();
        else
            contentLogicalLeft -= textIndentOffset();

        HTMLInputElement* button = uploadButton();
        if (!button)
            return;

        LayoutUnit buttonLogicalWidth = nodeLogicalWidth(button);
        LayoutUnit buttonAndIconLogicalWidth = buttonLogicalWidth + afterButtonSpacing
            + (inputElement().icon() ? iconLogicalWidth + iconFilenameSpacing : 0);
        LayoutUnit textLogicalLeft;
        if (writingMode().isLogicalLeftInlineStart())
            textLogicalLeft = contentLogicalLeft + buttonAndIconLogicalWidth;
        else
            textLogicalLeft = contentLogicalLeft + contentBoxLogicalWidth() - buttonAndIconLogicalWidth - font.width(textRun);

        // We want to match the button's baseline
        // FIXME: Make this work with transforms.
        auto textLogicalTop = [&]() -> float {
            if (auto* buttonRenderer = downcast<RenderButton>(button->renderer())) {
                if (auto* buttonTextRenderer = buttonRenderer->textRenderer()) {
                    if (auto textBox = InlineIterator::lineLeftmostTextBoxFor(*buttonTextRenderer)) {
                        auto textVisualRect = textBox->visualRectIgnoringBlockDirection();
                        textVisualRect.setLocation(buttonTextRenderer->localToContainerPoint(textVisualRect.location(), this));
                        textVisualRect.moveBy(roundPointToDevicePixels(paintOffset, document().deviceScaleFactor()));

                        auto metrics = textBox->style().fontCascade().metricsOfPrimaryFont();

                        if (!isHorizontalWritingMode) {
                            if (isBlockFlipped)
                                return textVisualRect.x() - metrics.intAscent();

                            return textVisualRect.x() + metrics.intDescent();
                        }

                        if (isBlockFlipped)
                            return textVisualRect.y() - metrics.intDescent();

                        return textVisualRect.y() + metrics.intAscent();
                    }
                }
            }

            return roundToInt(baselinePosition(AlphabeticBaseline, true, isHorizontalWritingMode ? HorizontalLine : VerticalLine, PositionOnContainingLine));
        }();

        paintInfo.context().setFillColor(style().visitedDependentColorWithColorFilter(CSSPropertyColor));
        
        // Draw the filename
        {
            GraphicsContextStateSaver stateSaver(paintInfo.context());

            if (writingMode().isLineOverLeft()) {
                textLogicalLeft += font.width(textRun);
                textLogicalTop += font.metricsOfPrimaryFont().intAscent();
            }

            auto textOrigin = IntPoint(roundToInt(textLogicalLeft), roundToInt(textLogicalTop));
            if (!isHorizontalWritingMode) {
                textOrigin = textOrigin.transposedPoint();

                paintInfo.context().translate(textOrigin);
                if (writingMode().isLineOverLeft())
                    paintInfo.context().rotate(-piOverTwoFloat);
                else
                    paintInfo.context().rotate(piOverTwoFloat);
                paintInfo.context().translate(-textOrigin);
            }

            paintInfo.context().drawBidiText(font, textRun, textOrigin);
        }

        if (inputElement().icon()) {
            // Determine where the icon should be placed
            LayoutUnit borderAndPaddingOffsetForIcon = (!isHorizontalWritingMode && isBlockFlipped) ? borderAndPaddingAfter() : borderAndPaddingBefore();
            LayoutUnit iconLogicalTop = logicalPaintOffset.y() + borderAndPaddingOffsetForIcon + (contentBoxLogicalHeight() - iconLogicalHeight) / 2;

            if (writingMode().isLineOverLeft())
                iconLogicalTop += (contentBoxLogicalHeight() - iconLogicalHeight) / 2;

            LayoutUnit iconLogicalLeft;
            if (writingMode().isLogicalLeftInlineStart())
                iconLogicalLeft = contentLogicalLeft + buttonLogicalWidth + afterButtonSpacing;
            else
                iconLogicalLeft = contentLogicalLeft + contentBoxLogicalWidth() - buttonLogicalWidth - afterButtonSpacing - iconLogicalWidth;

            IntRect iconRect(iconLogicalLeft, iconLogicalTop, iconLogicalWidth, iconLogicalHeight);
            if (!isHorizontalWritingMode)
                iconRect = iconRect.transposedRect();

#if PLATFORM(COCOA)
            if (RenderButton* buttonRenderer = downcast<RenderButton>(button->renderer())) {
                // Draw the file icon and decorations.
                auto decorationsType = inputElement().files()->length() == 1 ? RenderTheme::FileUploadDecorations::SingleFile : RenderTheme::FileUploadDecorations::MultipleFiles;
                theme().paintFileUploadIconDecorations(*this, *buttonRenderer, paintInfo, iconRect, inputElement().icon(), decorationsType);
            }
#else
            // Draw the file icon
            inputElement().icon()->paint(paintInfo.context(), iconRect);
#endif
        }
    }
}

void RenderFileUploadControl::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
    if (shouldApplySizeOrInlineSizeContainment()) {
        if (auto logicalWidth = explicitIntrinsicInnerLogicalWidth()) {
            minLogicalWidth = logicalWidth.value();
            maxLogicalWidth = logicalWidth.value();
        }
        return;
    }
    // Figure out how big the filename space needs to be for a given number of characters
    // (using "0" as the nominal character).
    const UChar character = '0';
    const String characterAsString = span(character);
    const FontCascade& font = style().fontCascade();
    // FIXME: Remove the need for this const_cast by making constructTextRun take a const RenderObject*.
    float minDefaultLabelWidth = defaultWidthNumChars * font.width(constructTextRun(characterAsString, style(), ExpansionBehavior::allowRightOnly()));

    const String label = theme().fileListDefaultLabel(inputElement().multiple());
    float defaultLabelWidth = font.width(constructTextRun(label, style(), ExpansionBehavior::allowRightOnly()));
    if (HTMLInputElement* button = uploadButton())
        if (RenderObject* buttonRenderer = button->renderer())
            defaultLabelWidth += buttonRenderer->maxPreferredLogicalWidth() + afterButtonSpacing;
    maxLogicalWidth = static_cast<int>(ceilf(std::max(minDefaultLabelWidth, defaultLabelWidth)));

    auto& logicalWidth = style().logicalWidth();
    if (logicalWidth.isCalculated())
        minLogicalWidth = std::max(0_lu, valueForLength(logicalWidth, 0_lu));
    else if (!logicalWidth.isPercent())
        minLogicalWidth = maxLogicalWidth;
}

void RenderFileUploadControl::computePreferredLogicalWidths()
{
    ASSERT(preferredLogicalWidthsDirty());

    m_minPreferredLogicalWidth = 0;
    m_maxPreferredLogicalWidth = 0;

    if (style().logicalWidth().isFixed() && style().logicalWidth().value() > 0)
        m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = adjustContentBoxLogicalWidthForBoxSizing(style().logicalWidth());
    else
        computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);

    RenderBox::computePreferredLogicalWidths(style().logicalMinWidth(), style().logicalMaxWidth(), writingMode().isHorizontal() ? horizontalBorderAndPaddingExtent() : verticalBorderAndPaddingExtent());

    setPreferredLogicalWidthsDirty(false);
}

VisiblePosition RenderFileUploadControl::positionForPoint(const LayoutPoint&, HitTestSource, const RenderFragmentContainer*)
{
    return VisiblePosition();
}

HTMLInputElement* RenderFileUploadControl::uploadButton() const
{
    ASSERT(inputElement().shadowRoot());
    return dynamicDowncast<HTMLInputElement>(inputElement().shadowRoot()->firstChild());
}

String RenderFileUploadControl::buttonValue()
{
    if (HTMLInputElement* button = uploadButton())
        return button->value();
    
    return String();
}

String RenderFileUploadControl::fileTextValue() const
{
    auto& input = inputElement();
    if (!input.files())
        return { };
    if (input.files()->length() && !input.displayString().isEmpty()) {
        if (input.files()->length() == 1)
            return StringTruncator::centerTruncate(input.displayString(), maxFilenameLogicalWidth(), style().fontCascade());

        return StringTruncator::rightTruncate(input.displayString(), maxFilenameLogicalWidth(), style().fontCascade());
    }
    return theme().fileListNameForWidth(input.files(), style().fontCascade(), maxFilenameLogicalWidth(), input.multiple());
}
    
} // namespace WebCore