/**
 * This file is part of the theme implementation for form controls in WebCore.
 *
 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Computer, Inc.
 *
 * 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 "RenderTheme.h"

#include "CSSValueKeywords.h"
#include "ColorUtilities.h"
#include "Document.h"
#include "FileList.h"
#include "FileSystem.h"
#include "FloatConversion.h"
#include "FocusController.h"
#include "FontSelector.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "GraphicsContext.h"
#include "HTMLAttachmentElement.h"
#include "HTMLButtonElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLProgressElement.h"
#include "HTMLSelectElement.h"
#include "HTMLTextAreaElement.h"
#include "InputType.h"
#include "LocalizedStrings.h"
#include "MediaControlElements.h"
#include "Page.h"
#include "PaintInfo.h"
#include "RenderStyle.h"
#include "RenderView.h"
#include "Settings.h"
#include "ShadowPseudoIds.h"
#include "SliderThumbElement.h"
#include "StringTruncator.h"
#include "TextControlInnerElements.h"
#include <wtf/Ref.h>

#if ENABLE(METER_ELEMENT)
#include "HTMLMeterElement.h"
#include "RenderMeter.h"
#endif

#if ENABLE(INPUT_SPEECH)
#include "RenderInputSpeech.h"
#endif

#if ENABLE(DATALIST_ELEMENT)
#include "HTMLCollection.h"
#include "HTMLDataListElement.h"
#include "HTMLOptionElement.h"
#include "HTMLParserIdioms.h"
#endif

// The methods in this file are shared by all themes on every platform.

namespace WebCore {

using namespace HTMLNames;

static Color& customFocusRingColor()
{
	static NeverDestroyed<Color> color;
    return color;
}

RenderTheme::RenderTheme()
#if USE(NEW_THEME)
    : m_theme(platformTheme())
#endif
{
}

void RenderTheme::adjustStyle(RenderStyle* style, const Element* element, const RenderStyle* userAgentAppearanceStyle)
{
    auto part = style->effectiveAppearance();
    if (part == AutoPart) {
        part = autoAppearanceForElement(element);

        ASSERT(part != AutoPart);
        style->setEffectiveAppearance(part);

        if (part == NoControlPart)
            return;
    }

    // Force inline and table display styles to be inline-block (except for table- which is block)
    if (style->display() == DisplayType::Inline || style->display() == DisplayType::InlineTable || style->display() == DisplayType::TableRowGroup ||
        style->display() == DisplayType::TableHeaderGroup || style->display() == DisplayType::TableFooterGroup ||
        style->display() == DisplayType::TableRow || style->display() == DisplayType::TableColumnGroup || style->display() == DisplayType::TableColumn ||
        style->display() == DisplayType::TableCell || style->display() == DisplayType::TableCaption)
        style->setEffectiveDisplay(DisplayType::InlineBlock);
    else if (style->display() == DisplayType::Compact || style->display() == DisplayType::ListItem || style->display() == DisplayType::Table)
        style->setEffectiveDisplay(DisplayType::Block);

    if (userAgentAppearanceStyle && isControlStyled(*style, *userAgentAppearanceStyle)) {
    	switch (part) {
		case MenulistPart:
			part = MenulistButtonPart;
			break;
		default:
			part = NoControlPart;
			break;
		}

		style->setEffectiveAppearance(part);
	}

    if (!style->hasEffectiveAppearance())
        return;

    // Never support box-shadow on native controls.
    style->setBoxShadow(nullptr);
    
#if USE(NEW_THEME)
    switch (part) {
        case CheckboxPart:
        case InnerSpinButtonPart:
        case RadioPart:
        case PushButtonPart:
        case SquareButtonPart:
        case DefaultButtonPart:
        case ButtonPart: {
            // Border
            LengthBox borderBox(style->borderTopWidth(), style->borderRightWidth(), style->borderBottomWidth(), style->borderLeftWidth());
            borderBox = m_theme->controlBorder(part, style->font(), borderBox, style->effectiveZoom());
            if (borderBox.top().value() != static_cast<int>(style->borderTopWidth())) {
                if (borderBox.top().value())
                    style->setBorderTopWidth(borderBox.top().value());
                else
                    style->resetBorderTop();
            }
            if (borderBox.right().value() != static_cast<int>(style->borderRightWidth())) {
                if (borderBox.right().value())
                    style->setBorderRightWidth(borderBox.right().value());
                else
                    style->resetBorderRight();
            }
            if (borderBox.bottom().value() != static_cast<int>(style->borderBottomWidth())) {
                style->setBorderBottomWidth(borderBox.bottom().value());
                if (borderBox.bottom().value())
                    style->setBorderBottomWidth(borderBox.bottom().value());
                else
                    style->resetBorderBottom();
            }
            if (borderBox.left().value() != static_cast<int>(style->borderLeftWidth())) {
                style->setBorderLeftWidth(borderBox.left().value());
                if (borderBox.left().value())
                    style->setBorderLeftWidth(borderBox.left().value());
                else
                    style->resetBorderLeft();
            }

            // Padding
            LengthBox paddingBox = m_theme->controlPadding(part, style->font(), style->paddingBox(), style->effectiveZoom());
            if (paddingBox != style->paddingBox())
                style->setPaddingBox(paddingBox);

            // Whitespace
            if (m_theme->controlRequiresPreWhiteSpace(part))
                style->setWhiteSpace(WhiteSpace::Pre);
            
            // Width / Height
            // The width and height here are affected by the zoom.
            // FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
            LengthSize controlSize = m_theme->controlSize(part, style->font(), LengthSize(style->width(), style->height()), style->effectiveZoom());
            if (controlSize.width() != style->width())
                style->setWidth(controlSize.width());
            if (controlSize.height() != style->height())
                style->setHeight(controlSize.height());
                
            // Min-Width / Min-Height
            LengthSize minControlSize = m_theme->minimumControlSize(part, style->font(), style->effectiveZoom());
            if (minControlSize.width.value() > style.minWidth().value())
				style.setMinWidth(WTFMove(minControlSize.width));
			if (minControlSize.height.value() > style.minHeight().value())
				style.setMinHeight(WTFMove(minControlSize.height));

	        // Font
	        if (auto themeFont = m_theme->controlFont(part, style.fontCascade(), style.effectiveZoom())) {
	            // If overriding the specified font with the theme font, also override the line height with the standard line height.
	            style.setLineHeight(RenderStyle::initialLineHeight());
	            if (style.setFontDescription(themeFont.value()))
	                style.fontCascade().update(nullptr);
	        }
        }
        default:
            break;
    }
#endif

    // Call the appropriate style adjustment method based off the appearance value.
    switch (part) {
#if !USE(NEW_THEME)
	case CheckboxPart:
		return adjustCheckboxStyle(style, element);
	case RadioPart:
		return adjustRadioStyle(style, element);
	case PushButtonPart:
	case SquareButtonPart:
	case DefaultButtonPart:
	case ButtonPart:
		return adjustButtonStyle(style, element);
	case InnerSpinButtonPart:
		return adjustInnerSpinButtonStyle(style, element);
#endif
	case TextFieldPart:
		return adjustTextFieldStyle(style, element);
	case TextAreaPart:
		return adjustTextAreaStyle(style, element);
	case MenulistPart:
		return adjustMenuListStyle(style, element);
	case MenulistButtonPart:
		return adjustMenuListButtonStyle(style, element);
	case MediaPlayButtonPart:
	case MediaCurrentTimePart:
	case MediaTimeRemainingPart:
	case MediaEnterFullscreenButtonPart:
	case MediaExitFullscreenButtonPart:
	case MediaMuteButtonPart:
	case MediaVolumeSliderContainerPart:
		return adjustMediaControlStyle(style, element);
	case MediaSliderPart:
	case MediaVolumeSliderPart:
	case MediaFullScreenVolumeSliderPart:
	case SliderHorizontalPart:
	case SliderVerticalPart:
		return adjustSliderTrackStyle(style, element);
	case SliderThumbHorizontalPart:
	case SliderThumbVerticalPart:
		return adjustSliderThumbStyle(style, element);
	case SearchFieldPart:
		return adjustSearchFieldStyle(style, element);
	case SearchFieldCancelButtonPart:
		return adjustSearchFieldCancelButtonStyle(style, element);
	case SearchFieldDecorationPart:
		return adjustSearchFieldDecorationStyle(style, element);
	case SearchFieldResultsDecorationPart:
		return adjustSearchFieldResultsDecorationStyle(style, element);
	case SearchFieldResultsButtonPart:
		return adjustSearchFieldResultsButtonStyle(style, element);
#if ENABLE(PROGRESS_ELEMENT)
	case ProgressBarPart:
		return adjustProgressBarStyle(style, element);
#endif
#if ENABLE(METER_ELEMENT)
	case MeterPart:
	case RelevancyLevelIndicatorPart:
	case ContinuousCapacityLevelIndicatorPart:
	case DiscreteCapacityLevelIndicatorPart:
	case RatingLevelIndicatorPart:
		return adjustMeterStyle(style, element);
#endif
#if ENABLE(INPUT_SPEECH)
	case InputSpeechButtonPart:
		return adjustInputFieldSpeechButtonStyle(style, element);
#endif
#if ENABLE(DATALIST_ELEMENT)
	case ListButtonPart:
		return adjustListButtonStyle(*style, element);
#endif
	default:
		break;
    }
}

ControlPart RenderTheme::autoAppearanceForElement(const Element* elementPtr) const
{
    if (!elementPtr)
        return NoControlPart;

    Ref<const Element> element = *elementPtr;

    if (isHTMLInputElement(element)) {
        auto& input = toHTMLInputElement(element.get());

        if (input.isTextButton() || input.isUploadButton())
            return PushButtonPart;

        if (input.isCheckbox())
            return CheckboxPart;

        if (input.isRadioButton())
            return RadioPart;

        if (input.isSearchField())
            return SearchFieldPart;

        if (input.isDateField() || input.isDateTimeLocalField() || input.isMonthField() || input.isTimeField() || input.isWeekField()) {
#if PLATFORM(IOS_FAMILY)
            return MenulistButtonPart;
#else
            return TextFieldPart;
#endif
        }

#if ENABLE(INPUT_TYPE_COLOR) && !PLATFORM(ESPIAL)
        if (input.isColorControl())
            return ColorWellPart;
#endif

        if (input.isRangeControl())
            return SliderHorizontalPart;

        if (input.isTextField())
            return TextFieldPart;

        // <input type=hidden|image|file>
        return NoControlPart;
    }

    if (isHTMLButtonElement(element))
        return ButtonPart;

    if (isHTMLSelectElement(element)) {
#if PLATFORM(IOS_FAMILY)
        return MenulistButtonPart;
#else
        auto& select = toHTMLSelectElement(element.get());
        return select.usesMenuList() ? MenulistPart : ListboxPart;
#endif
    }

    if (isHTMLTextAreaElement(element))
        return TextAreaPart;

    if (isHTMLMeterElement(element))
        return MeterPart;

    if (isHTMLProgressElement(element))
        return ProgressBarPart;

#if ENABLE(ATTACHMENT_ELEMENT)
    if (is<HTMLAttachmentElement>(element))
        return AttachmentPart;
#endif

    if (element->isInUserAgentShadowTree()) {
        auto& pseudo = element->shadowPseudoId();

#if ENABLE(DATALIST_ELEMENT)
        if (pseudo == ShadowPseudoIds::webkitListButton())
            return ListButtonPart;
#endif

        if (pseudo == ShadowPseudoIds::webkitCapsLockIndicator())
            return CapsLockIndicatorPart;

        if (pseudo == ShadowPseudoIds::webkitSearchCancelButton())
            return SearchFieldCancelButtonPart;

        if (pseudo == ShadowPseudoIds::webkitSearchDecoration())
            return SearchFieldDecorationPart;

        if (pseudo == ShadowPseudoIds::webkitSearchResultsDecoration())
            return SearchFieldResultsDecorationPart;

        if (pseudo == ShadowPseudoIds::webkitSearchResultsButton())
            return SearchFieldResultsButtonPart;

        if (pseudo == ShadowPseudoIds::webkitSliderThumb() || pseudo == ShadowPseudoIds::webkitMediaSliderThumb())
            return SliderThumbHorizontalPart;

        if (pseudo == ShadowPseudoIds::webkitInnerSpinButton())
            return InnerSpinButtonPart;
    }

    return NoControlPart;
}

#if 0
void RenderTheme::adjustSearchFieldDecorationStyle(RenderStyle& style, const Element* element) const
{
    if (is<SearchFieldResultsButtonElement>(element) && !downcast<SearchFieldResultsButtonElement>(*element).canAdjustStyleForAppearance()) {
        style.setEffectiveAppearance(NoControlPart);
        return;
    }

    switch (style.effectiveAppearance()) {
    case SearchFieldDecorationPart:
        return adjustSearchFieldDecorationPartStyle(style, element);
    case SearchFieldResultsDecorationPart:
        return adjustSearchFieldResultsDecorationPartStyle(style, element);
    case SearchFieldResultsButtonPart:
        return adjustSearchFieldResultsButtonStyle(style, element);
    default:
        break;
    }
}
#endif

bool RenderTheme::paint(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
{
    // If painting is disabled, but we aren't updating control tints, then just bail.
    // If we are updating control tints, just schedule a repaint if the theme supports tinting
    // for that control.
    if (paintInfo.context->updatingControlTints()) {
        if (controlSupportsTints(o))
            o->repaint();
        return false;
    }
    if (paintInfo.context->paintingDisabled())
        return false;

    ControlPart part = o->style()->effectiveAppearance();

#if USE(NEW_THEME)
    switch (part) {
        case CheckboxPart:
        case RadioPart:
        case PushButtonPart:
        case SquareButtonPart:
        case DefaultButtonPart:
        case ButtonPart:
        case InnerSpinButtonPart:
            m_theme->paint(part, controlStatesForRenderer(o), const_cast<GraphicsContext*>(paintInfo.context), r, o->style()->effectiveZoom(), &o->view().frameView());
            return false;
        default:
            break;
    }
#endif

    // Call the appropriate paint method based off the appearance value.
    switch (part) {
#if !USE(NEW_THEME)
        case CheckboxPart:
            return paintCheckbox(o, paintInfo, r);
        case RadioPart:
            return paintRadio(o, paintInfo, r);
        case PushButtonPart:
        case SquareButtonPart:
        case DefaultButtonPart:
        case ButtonPart:
            return paintButton(o, paintInfo, r);
        case InnerSpinButtonPart:
            return paintInnerSpinButton(o, paintInfo, r);
#endif
        case MenulistPart:
            return paintMenuList(o, paintInfo, r);
#if ENABLE(METER_ELEMENT)
        case MeterPart:
        case RelevancyLevelIndicatorPart:
        case ContinuousCapacityLevelIndicatorPart:
        case DiscreteCapacityLevelIndicatorPart:
        case RatingLevelIndicatorPart:
            return paintMeter(o, paintInfo, r);
#endif
#if ENABLE(PROGRESS_ELEMENT)
        case ProgressBarPart:
            return paintProgressBar(o, paintInfo, r);
#endif
        case SliderHorizontalPart:
        case SliderVerticalPart:
            return paintSliderTrack(o, paintInfo, r);
        case SliderThumbHorizontalPart:
        case SliderThumbVerticalPart:
            return paintSliderThumb(o, paintInfo, r);
        case MediaEnterFullscreenButtonPart:
        case MediaExitFullscreenButtonPart:
            return paintMediaFullscreenButton(o, paintInfo, r);
        case MediaPlayButtonPart:
            return paintMediaPlayButton(o, paintInfo, r);
        case MediaMuteButtonPart:
            return paintMediaMuteButton(o, paintInfo, r);
        case MediaSeekBackButtonPart:
            return paintMediaSeekBackButton(o, paintInfo, r);
        case MediaSeekForwardButtonPart:
            return paintMediaSeekForwardButton(o, paintInfo, r);
        case MediaRewindButtonPart:
            return paintMediaRewindButton(o, paintInfo, r);
        case MediaReturnToRealtimeButtonPart:
            return paintMediaReturnToRealtimeButton(o, paintInfo, r);
        case MediaToggleClosedCaptionsButtonPart:
            return paintMediaToggleClosedCaptionsButton(o, paintInfo, r);
        case MediaSliderPart:
            return paintMediaSliderTrack(o, paintInfo, r);
        case MediaSliderThumbPart:
            return paintMediaSliderThumb(o, paintInfo, r);
        case MediaVolumeSliderMuteButtonPart:
            return paintMediaMuteButton(o, paintInfo, r);
        case MediaVolumeSliderContainerPart:
            return paintMediaVolumeSliderContainer(o, paintInfo, r);
        case MediaVolumeSliderPart:
            return paintMediaVolumeSliderTrack(o, paintInfo, r);
        case MediaVolumeSliderThumbPart:
            return paintMediaVolumeSliderThumb(o, paintInfo, r);
        case MediaFullScreenVolumeSliderPart:
            return paintMediaFullScreenVolumeSliderTrack(o, paintInfo, r);
        case MediaFullScreenVolumeSliderThumbPart:
            return paintMediaFullScreenVolumeSliderThumb(o, paintInfo, r);
        case MediaTimeRemainingPart:
            return paintMediaTimeRemaining(o, paintInfo, r);
        case MediaCurrentTimePart:
            return paintMediaCurrentTime(o, paintInfo, r);
        case MediaControlsBackgroundPart:
            return paintMediaControlsBackground(o, paintInfo, r);
        case MenulistButtonPart:
        case TextFieldPart:
        case TextAreaPart:
        case ListboxPart:
            return true;
        case SearchFieldPart:
            return paintSearchField(o, paintInfo, r);
        case SearchFieldCancelButtonPart:
            return paintSearchFieldCancelButton(o, paintInfo, r);
        case SearchFieldDecorationPart:
            return paintSearchFieldDecoration(o, paintInfo, r);
        case SearchFieldResultsDecorationPart:
            return paintSearchFieldResultsDecoration(o, paintInfo, r);
        case SearchFieldResultsButtonPart:
            return paintSearchFieldResultsButton(o, paintInfo, r);
#if ENABLE(INPUT_SPEECH)
        case InputSpeechButtonPart:
            return paintInputFieldSpeechButton(o, paintInfo, r);
#endif
        default:
            break;
    }

    return true; // We don't support the appearance, so let the normal background/border paint.
}

bool RenderTheme::paintBorderOnly(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
{
    if (paintInfo.context->paintingDisabled())
        return false;

#if PLATFORM(IOS)
    UNUSED_PARAM(r);
    return o->style().effectiveAppearance() != NoControlPart;
#else
    // Call the appropriate paint method based off the appearance value.
    switch (o->style()->effectiveAppearance()) {
        case TextFieldPart:
            return paintTextField(o, paintInfo, r);
        case ListboxPart:
        case TextAreaPart:
            return paintTextArea(o, paintInfo, r);
        case MenulistButtonPart:
        case SearchFieldPart:
            return true;
        case CheckboxPart:
        case RadioPart:
        case PushButtonPart:
        case SquareButtonPart:
        case DefaultButtonPart:
        case ButtonPart:
        case MenulistPart:
#if ENABLE(METER_ELEMENT)
        case MeterPart:
        case RelevancyLevelIndicatorPart:
        case ContinuousCapacityLevelIndicatorPart:
        case DiscreteCapacityLevelIndicatorPart:
        case RatingLevelIndicatorPart:
#endif
#if ENABLE(PROGRESS_ELEMENT)
        case ProgressBarPart:
#endif
        case SliderHorizontalPart:
        case SliderVerticalPart:
        case SliderThumbHorizontalPart:
        case SliderThumbVerticalPart:
        case SearchFieldCancelButtonPart:
        case SearchFieldDecorationPart:
        case SearchFieldResultsDecorationPart:
        case SearchFieldResultsButtonPart:
#if ENABLE(INPUT_SPEECH)
        case InputSpeechButtonPart:
#endif
        default:
            break;
    }

    return false;
#endif
}

bool RenderTheme::paintDecorations(RenderObject* renderer, const PaintInfo& paintInfo, const IntRect& rect)
{
    if (paintInfo.context->paintingDisabled())
        return false;

    // Call the appropriate paint method based off the appearance value.
    switch (renderer->style()->effectiveAppearance()) {
        case MenulistButtonPart:
            return paintMenuListButton(renderer, paintInfo, rect);
        case TextFieldPart:
            return paintTextFieldDecorations(renderer, paintInfo, rect);
        case TextAreaPart:
            return paintTextAreaDecorations(renderer, paintInfo, rect);
        case CheckboxPart:
            return paintCheckboxDecorations(renderer, paintInfo, rect);
        case RadioPart:
            return paintRadioDecorations(renderer, paintInfo, rect);
        case PushButtonPart:
            return paintPushButtonDecorations(renderer, paintInfo, rect);
        case SquareButtonPart:
            return paintSquareButtonDecorations(renderer, paintInfo, rect);
        case ButtonPart:
            return paintButtonDecorations(renderer, paintInfo, rect);
        case MenulistPart:
            return paintMenuListDecorations(renderer, paintInfo, rect);
        case SliderThumbHorizontalPart:
        case SliderThumbVerticalPart:
            return paintSliderThumbDecorations(renderer, paintInfo, rect);
        case SearchFieldPart:
            return paintSearchFieldDecorations(renderer, paintInfo, rect);
#if ENABLE(METER_ELEMENT)
        case MeterPart:
        case RelevancyLevelIndicatorPart:
        case ContinuousCapacityLevelIndicatorPart:
        case DiscreteCapacityLevelIndicatorPart:
        case RatingLevelIndicatorPart:
#endif
#if ENABLE(PROGRESS_ELEMENT)
        case ProgressBarPart:
#endif
        case SliderHorizontalPart:
        case SliderVerticalPart:
        case ListboxPart:
        case DefaultButtonPart:
        case SearchFieldCancelButtonPart:
        case SearchFieldDecorationPart:
        case SearchFieldResultsDecorationPart:
        case SearchFieldResultsButtonPart:
#if ENABLE(INPUT_SPEECH)
        case InputSpeechButtonPart:
#endif
        default:
            break;
    }

    return false;
}

#if ENABLE(VIDEO)

String RenderTheme::formatMediaControlsTime(float time) const
{
    if (!isfinite(time))
        time = 0;
    int seconds = (int)fabsf(time);
    int hours = seconds / (60 * 60);
    int minutes = (seconds / 60) % 60;
    seconds %= 60;
    if (hours) {
        if (hours > 9)
            return String::format("%s%02d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds);

        return String::format("%s%01d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds);
    }

    return String::format("%s%02d:%02d", (time < 0 ? "-" : ""), minutes, seconds);
}

String RenderTheme::formatMediaControlsCurrentTime(float currentTime, float /*duration*/) const
{
    return formatMediaControlsTime(currentTime);
}

String RenderTheme::formatMediaControlsRemainingTime(float currentTime, float duration) const
{
    return formatMediaControlsTime(currentTime - duration);
}

LayoutPoint RenderTheme::volumeSliderOffsetFromMuteButton(RenderBox* muteButtonBox, const LayoutSize& size) const
{
	LayoutUnit y = -size.height();
    FloatPoint absPoint = muteButtonBox->localToAbsolute(FloatPoint(muteButtonBox->offsetLeft(), y), OptionSet<MapCoordinatesMode>(IsFixed, UseTransforms));
    if (absPoint.y() < 0)
        y = muteButtonBox->height();
    return LayoutPoint(0, y);
}

#endif

Color RenderTheme::activeSelectionBackgroundColor() const
{
    if (!m_activeSelectionBackgroundColor.isValid())
        m_activeSelectionBackgroundColor = transformSelectionBackgroundColor(platformActiveSelectionBackgroundColor());
    return m_activeSelectionBackgroundColor;
}

Color RenderTheme::inactiveSelectionBackgroundColor() const
{
    if (!m_inactiveSelectionBackgroundColor.isValid())
        m_inactiveSelectionBackgroundColor = transformSelectionBackgroundColor(platformInactiveSelectionBackgroundColor());
    return m_inactiveSelectionBackgroundColor;
}

Color RenderTheme::transformSelectionBackgroundColor(const Color& color) const
{
    return color.blendWithWhite();
}

Color RenderTheme::activeSelectionForegroundColor() const
{
    if (!m_activeSelectionForegroundColor.isValid() && supportsSelectionForegroundColors())
        m_activeSelectionForegroundColor = platformActiveSelectionForegroundColor();
    return m_activeSelectionForegroundColor;
}

Color RenderTheme::inactiveSelectionForegroundColor() const
{
    if (!m_inactiveSelectionForegroundColor.isValid() && supportsSelectionForegroundColors())
        m_inactiveSelectionForegroundColor = platformInactiveSelectionForegroundColor();
    return m_inactiveSelectionForegroundColor;
}

Color RenderTheme::activeListBoxSelectionBackgroundColor() const
{
    if (!m_activeListBoxSelectionBackgroundColor.isValid())
        m_activeListBoxSelectionBackgroundColor = platformActiveListBoxSelectionBackgroundColor();
    return m_activeListBoxSelectionBackgroundColor;
}

Color RenderTheme::inactiveListBoxSelectionBackgroundColor() const
{
    if (!m_inactiveListBoxSelectionBackgroundColor.isValid())
        m_inactiveListBoxSelectionBackgroundColor = platformInactiveListBoxSelectionBackgroundColor();
    return m_inactiveListBoxSelectionBackgroundColor;
}

Color RenderTheme::activeListBoxSelectionForegroundColor() const
{
    if (!m_activeListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors())
        m_activeListBoxSelectionForegroundColor = platformActiveListBoxSelectionForegroundColor();
    return m_activeListBoxSelectionForegroundColor;
}

Color RenderTheme::inactiveListBoxSelectionForegroundColor() const
{
    if (!m_inactiveListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors())
        m_inactiveListBoxSelectionForegroundColor = platformInactiveListBoxSelectionForegroundColor();
    return m_inactiveListBoxSelectionForegroundColor;
}

Color RenderTheme::platformActiveSelectionBackgroundColor() const
{
    // Use a blue color by default if the platform theme doesn't define anything.
    return Color(0, 0, 255);
}

Color RenderTheme::platformActiveSelectionForegroundColor() const
{
    // Use a white color by default if the platform theme doesn't define anything.
    return Color::white;
}

Color RenderTheme::platformInactiveSelectionBackgroundColor() const
{
    // Use a grey color by default if the platform theme doesn't define anything.
    // This color matches Firefox's inactive color.
    return Color(176, 176, 176);
}

Color RenderTheme::platformInactiveSelectionForegroundColor() const
{
    // Use a black color by default.
    return Color::black;
}

Color RenderTheme::platformActiveListBoxSelectionBackgroundColor() const
{
    return platformActiveSelectionBackgroundColor();
}

Color RenderTheme::platformActiveListBoxSelectionForegroundColor() const
{
    return platformActiveSelectionForegroundColor();
}

Color RenderTheme::platformInactiveListBoxSelectionBackgroundColor() const
{
    return platformInactiveSelectionBackgroundColor();
}

Color RenderTheme::platformInactiveListBoxSelectionForegroundColor() const
{
    return platformInactiveSelectionForegroundColor();
}

#if ENABLE(CALENDAR_PICKER)
CString RenderTheme::extraCalendarPickerStyleSheet()
{
    return CString();
}
#endif

int RenderTheme::baselinePosition(const RenderObject* o) const
{
    if (!o->isBox())
        return 0;

    const RenderBox* box = toRenderBox(o);

#if USE(NEW_THEME)
    return box->height() + box->marginTop() + m_theme->baselinePositionAdjustment(o->style()->effectiveAppearance()) * o->style()->effectiveZoom();
#else
    return box->height() + box->marginTop();
#endif
}

bool RenderTheme::isControlContainer(ControlPart appearance) const
{
    // There are more leaves than this, but we'll patch this function as we add support for
    // more controls.
    return appearance != CheckboxPart && appearance != RadioPart;
}

bool RenderTheme::isControlStyled(const RenderStyle& style, const RenderStyle& userAgentStyle) const
{
    switch (style.effectiveAppearance()) {
        case PushButtonPart:
        case SquareButtonPart:
        case DefaultButtonPart:
        case ButtonPart:
        case ListboxPart:
        case MenulistPart:
        case ProgressBarPart:
        case MeterPart:
        case RelevancyLevelIndicatorPart:
        case ContinuousCapacityLevelIndicatorPart:
        case DiscreteCapacityLevelIndicatorPart:
        case RatingLevelIndicatorPart:
		// FIXME: SearchFieldPart should be included here when making search fields style-able.
		case TextFieldPart:
        case TextAreaPart:
            // Test the style to see if the UA border and background match.
            return style.border() != userAgentStyle.border()
                || style.backgroundLayers() != userAgentStyle.backgroundLayers()
                || !style.backgroundColorEqualsToColorIgnoringVisited(userAgentStyle.backgroundColor());
        default:
            return false;
    }
}

void RenderTheme::adjustRepaintRect(const RenderObject* o, FloatRect& r)
{
#if USE(NEW_THEME)
    m_theme->inflateControlPaintRect(o->style()->effectiveAppearance(), controlStatesForRenderer(o), r, o->style()->effectiveZoom());
#endif
}

bool RenderTheme::supportsFocusRing(const RenderStyle* style) const
{
    return (style->hasEffectiveAppearance() && style->effectiveAppearance() != TextFieldPart && style->effectiveAppearance() != TextAreaPart && style->effectiveAppearance() != MenulistButtonPart && style->effectiveAppearance() != ListboxPart);
}

bool RenderTheme::stateChanged(RenderObject* o, ControlState state) const
{
    // Default implementation assumes the controls don't respond to changes in :hover state
    if (state == HoverState && !supportsHover(o->style()))
        return false;

    // Assume pressed state is only responded to if the control is enabled.
    if (state == PressedState && !isEnabled(o))
        return false;

    // Repaint the control.
    o->repaint();
    return true;
}

ControlStates RenderTheme::controlStatesForRenderer(const RenderObject* o) const
{
    ControlStates result = 0;
    if (isHovered(o)) {
        result |= HoverState;
        if (isSpinUpButtonPartHovered(o))
            result |= SpinUpState;
    }
    if (isPressed(o)) {
        result |= PressedState;
        if (isSpinUpButtonPartPressed(o))
            result |= SpinUpState;
    }
    if (isFocused(o) && o->style()->outlineStyleIsAuto())
        result |= FocusState;
    if (isEnabled(o))
        result |= EnabledState;
    if (isChecked(o))
        result |= CheckedState;
    if (isDefault(o))
        result |= DefaultState;
    if (!isActive(o))
        result |= WindowInactiveState;
    if (isIndeterminate(o))
        result |= IndeterminateState;
    return result;
}

bool RenderTheme::isActive(const RenderObject* o) const
{
    Node* node = o->node();
    if (!node)
        return false;

    Frame* frame = node->document().frame();
    if (!frame)
        return false;

    Page* page = frame->page();
    if (!page)
        return false;

    return page->focusController()->isActive();
}

bool RenderTheme::isChecked(const RenderObject* o) const
{
    if (!o->node())
        return false;

    auto* inputElement = o->node()->toInputElement();
    if (!inputElement)
        return false;

    return inputElement->shouldAppearChecked();
}

bool RenderTheme::isIndeterminate(const RenderObject* o) const
{
    if (!o->node())
        return false;

    auto* inputElement = o->node()->toInputElement();
    if (!inputElement)
        return false;

    return inputElement->shouldAppearIndeterminate();
}

bool RenderTheme::isEnabled(const RenderObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode())
        return true;
    return !toElement(node)->isDisabledFormControl();
}

bool RenderTheme::isFocused(const RenderObject* renderer) const
{
    Node* node = renderer->node();
    if (!node || !node->isElementNode())
        return false;

    RefPtr<Element> element = toElement(node);

    RefPtr<Element> delegate = element;
	if (element->isSliderThumbElement())
		delegate = toSliderThumbElement(*element).hostInput();

	Document& document = delegate->document();
    return delegate  == document.focusedElement() && document.selection().isFocusedAndActive();
}

bool RenderTheme::isPressed(const RenderObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode())
        return false;
    return toElement(node)->active();
}

bool RenderTheme::isSpinUpButtonPartPressed(const RenderObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode())
        return false;
    Element* element = toElement(node);
    if (!element->active() || !element->isSpinButtonElement())
        return false;
    return static_cast<SpinButtonElement*>(element)->upDownState() == SpinButtonElement::Up;
}

bool RenderTheme::isReadOnlyControl(const RenderObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode()|| !toElement(node)->isFormControlElement())
        return false;
    return !static_cast<Element*>(node)->matchesReadWritePseudoClass();
}

bool RenderTheme::isHovered(const RenderObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode())
        return false;
    if (!static_cast<Element*>(node)->isSpinButtonElement())
        return toElement(node)->hovered();
    SpinButtonElement* element = static_cast<SpinButtonElement*>(node);
    return element->hovered() && element->upDownState() != SpinButtonElement::Indeterminate;
}

bool RenderTheme::isSpinUpButtonPartHovered(const RenderObject* o) const
{
    Node* node = o->node();
    if (!node || !node->isElementNode() || !static_cast<Element*>(node)->isSpinButtonElement())
        return false;
    SpinButtonElement* element = static_cast<SpinButtonElement*>(node);
    return element->upDownState() == SpinButtonElement::Up;
}

bool RenderTheme::isDefault(const RenderObject* o) const
{
    // A button should only have the default appearance if the page is active
    if (!isActive(o))
        return false;

    if (!o->document().settings().inApplicationChromeMode())
        return false;
    
    return o->style()->effectiveAppearance() == DefaultButtonPart;
}

#if !USE(NEW_THEME)

void RenderTheme::adjustCheckboxStyle(RenderStyle* style, const Element*) const
{
    // A summary of the rules for checkbox designed to match WinIE:
    // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.)
    // font-size - not honored (control has no text), but we use it to decide which control size to use.
    setCheckboxSize(style);

    // padding - not honored by WinIE, needs to be removed.
    style->resetPadding();

    // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme)
    // for now, we will not honor it.
    style->resetBorder();

    style->setBoxShadow(nullptr);
}

void RenderTheme::adjustRadioStyle(RenderStyle* style, const Element*) const
{
    // A summary of the rules for checkbox designed to match WinIE:
    // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.)
    // font-size - not honored (control has no text), but we use it to decide which control size to use.
    setRadioSize(style);

    // padding - not honored by WinIE, needs to be removed.
    style->resetPadding();

    // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme)
    // for now, we will not honor it.
    style->resetBorder();

    style->setBoxShadow(nullptr);
}

void RenderTheme::adjustButtonStyle(RenderStyle* style, const Element*) const
{
    // Most platforms will completely honor all CSS, and so we have no need to adjust the style
    // at all by default.  We will still allow the theme a crack at setting up a desired vertical size.
    setButtonSize(style);
}

void RenderTheme::adjustInnerSpinButtonStyle(RenderStyle*, const Element*) const
{
}
#endif

void RenderTheme::adjustTextFieldStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustTextAreaStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustMenuListStyle(RenderStyle*, const Element*) const
{
}

#if ENABLE(INPUT_SPEECH)
void RenderTheme::adjustInputFieldSpeechButtonStyle(RenderStyle* style, const Element* element) const
{
    RenderInputSpeech::adjustInputFieldSpeechButtonStyle(style, element);
}

bool RenderTheme::paintInputFieldSpeechButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
    return RenderInputSpeech::paintInputFieldSpeechButton(object, paintInfo, rect);
}
#endif

#if ENABLE(METER_ELEMENT)
void RenderTheme::adjustMeterStyle(RenderStyle* style, const Element*) const
{
    style->setBoxShadow(nullptr);
}

IntSize RenderTheme::meterSizeForBounds(const RenderMeter*, const IntRect& bounds) const
{
    return bounds.size();
}

bool RenderTheme::supportsMeter(ControlPart) const
{
    return false;
}

bool RenderTheme::paintMeter(RenderObject*, const PaintInfo&, const IntRect&)
{
    return true;
}

#endif

#if ENABLE(DATALIST_ELEMENT)
void RenderTheme::paintSliderTicks(RenderObject* o, const PaintInfo& paintInfo, const IntRect& rect)
{
    Node* node = o->node();
    if (!node)
        return;

    auto* input = node->toInputElement();
    if (!input)
        return;

    HTMLDataListElement* dataList = static_cast<HTMLDataListElement*>(input->list());
    if (!dataList)
        return;

    double min = input->minimum();
    double max = input->maximum();
    ControlPart part = o->style()->effectiveAppearance();
    // We don't support ticks on alternate sliders like MediaVolumeSliders.
    if (part !=  SliderHorizontalPart && part != SliderVerticalPart)
        return;
    bool isHorizontal = part ==  SliderHorizontalPart;

    IntSize thumbSize;
    RenderObject* thumbRenderer = input->sliderThumbElement()->renderer();
    if (thumbRenderer) {
        auto* thumbStyle = thumbRenderer->style();
        int thumbWidth = thumbStyle->width().intValue();
        int thumbHeight = thumbStyle->height().intValue();
        thumbSize.setWidth(isHorizontal ? thumbWidth : thumbHeight);
        thumbSize.setHeight(isHorizontal ? thumbHeight : thumbWidth);
    }

    IntSize tickSize = sliderTickSize();
    float zoomFactor = o->style()->effectiveZoom();
    FloatRect tickRect;
    int tickRegionSideMargin = 0;
    int tickRegionWidth = 0;
    IntRect trackBounds;
    RenderObject* trackRenderer = input->sliderTrackElement()->renderer();
    // We can ignoring transforms because transform is handled by the graphics context.
    if (trackRenderer)
        trackBounds = trackRenderer->absoluteBoundingBoxRectIgnoringTransforms();
    IntRect sliderBounds = o->absoluteBoundingBoxRectIgnoringTransforms();

    // Make position relative to the transformed ancestor element.
    trackBounds.setX(trackBounds.x() - sliderBounds.x() + rect.x());
    trackBounds.setY(trackBounds.y() - sliderBounds.y() + rect.y());

    if (isHorizontal) {
        tickRect.setWidth(floor(tickSize.width() * zoomFactor));
        tickRect.setHeight(floor(tickSize.height() * zoomFactor));
        tickRect.setY(floor(rect.y() + rect.height() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor));
        tickRegionSideMargin = trackBounds.x() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0;
        tickRegionWidth = trackBounds.width() - thumbSize.width();
    } else {
        tickRect.setWidth(floor(tickSize.height() * zoomFactor));
        tickRect.setHeight(floor(tickSize.width() * zoomFactor));
        tickRect.setX(floor(rect.x() + rect.width() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor));
        tickRegionSideMargin = trackBounds.y() + (thumbSize.width() - tickSize.width() * zoomFactor) / 2.0;
		tickRegionWidth = trackBounds.height() - thumbSize.width();
    }
    RefPtr<HTMLCollection> options = dataList->options();
    GraphicsContextStateSaver stateSaver(*paintInfo.context);
    paintInfo.context->setFillColor(o->style()->visitedDependentColorWithColorFilter(CSSPropertyColor));
    for (unsigned i = 0; Node* node = options->item(i); i++) {
        ASSERT(node->hasTagName(optionTag));
        HTMLOptionElement* optionElement = static_cast<HTMLOptionElement*>(node);
        String value = optionElement->value();
        if (!input->isValidValue(value))
            continue;
        double parsedValue = parseToDoubleForNumberType(input->sanitizeValue(value));
        double tickFraction = (parsedValue - min) / (max - min);
		double tickRatio = isHorizontal && o->style()->isLeftToRightDirection() ? tickFraction : 1.0 - tickFraction;
		double tickPosition = round(tickRegionSideMargin + tickRegionWidth * tickRatio);
		if (isHorizontal)
			tickRect.setX(tickPosition);
		else
			tickRect.setY(tickPosition);
        paintInfo.context->fillRect(tickRect);
    }
}
#endif

#if ENABLE(DATALIST_ELEMENT)

void RenderTheme::adjustListButtonStyle(RenderStyle&, const Element*) const
{
}
#endif

#if ENABLE(PROGRESS_ELEMENT)
double RenderTheme::animationRepeatIntervalForProgressBar(RenderProgress*) const
{
    return 0;
}

double RenderTheme::animationDurationForProgressBar(RenderProgress*) const
{
    return 0;
}

void RenderTheme::adjustProgressBarStyle(RenderStyle*, const Element*) const
{
}
#endif

bool RenderTheme::shouldHaveSpinButton(const HTMLInputElement* inputElement) const
{
    return inputElement->isSteppable() &&
    	!inputElement->isRangeControl() &&
    	!inputElement->isDateField() &&
    	!inputElement->isDateTimeLocalField() &&
    	!inputElement->isMonthField() &&
    	!inputElement->isTimeField()&&
    	!inputElement->isWeekField();
}

bool RenderTheme::shouldHaveCapsLockIndicator(const HTMLInputElement&) const
{
	return false;
}

void RenderTheme::adjustMenuListButtonStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustMediaControlStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustSliderTrackStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustSliderThumbStyle(RenderStyle* style, const Element* element) const
{
    adjustSliderThumbSize(style, element);
}

void RenderTheme::adjustSliderThumbSize(RenderStyle*, const  Element*) const
{
}

void RenderTheme::adjustSearchFieldStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustSearchFieldCancelButtonStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustSearchFieldDecorationStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustSearchFieldResultsDecorationStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::adjustSearchFieldResultsButtonStyle(RenderStyle*, const Element*) const
{
}

void RenderTheme::platformColorsDidChange()
{
    m_activeSelectionForegroundColor = Color();
    m_inactiveSelectionForegroundColor = Color();
    m_activeSelectionBackgroundColor = Color();
    m_inactiveSelectionBackgroundColor = Color();

    m_activeListBoxSelectionForegroundColor = Color();
    m_inactiveListBoxSelectionForegroundColor = Color();
    m_activeListBoxSelectionBackgroundColor = Color();
    m_inactiveListBoxSelectionForegroundColor = Color();

    Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment();
}

Color RenderTheme::systemColor(CSSValueID cssValueId) const
{
    switch (cssValueId) {
        case CSSValueActiveborder:
            return 0xFFFFFFFF;
        case CSSValueActivecaption:
            return 0xFFCCCCCC;
        case CSSValueAppworkspace:
            return 0xFFFFFFFF;
        case CSSValueBackground:
            return 0xFF6363CE;
        case CSSValueButtonface:
            return 0xFFC0C0C0;
        case CSSValueButtonhighlight:
            return 0xFFDDDDDD;
        case CSSValueButtonshadow:
            return 0xFF888888;
        case CSSValueButtontext:
            return 0xFF000000;
        case CSSValueCaptiontext:
            return 0xFF000000;
        case CSSValueGraytext:
            return 0xFF808080;
        case CSSValueHighlight:
            return 0xFFB5D5FF;
        case CSSValueHighlighttext:
            return 0xFF000000;
        case CSSValueInactiveborder:
            return 0xFFFFFFFF;
        case CSSValueInactivecaption:
            return 0xFFFFFFFF;
        case CSSValueInactivecaptiontext:
            return 0xFF7F7F7F;
        case CSSValueInfobackground:
            return 0xFFFBFCC5;
        case CSSValueInfotext:
            return 0xFF000000;
        case CSSValueMenu:
            return 0xFFC0C0C0;
        case CSSValueMenutext:
            return 0xFF000000;
        case CSSValueScrollbar:
            return 0xFFFFFFFF;
        case CSSValueText:
            return 0xFF000000;
        case CSSValueThreeddarkshadow:
            return 0xFF666666;
        case CSSValueThreedface:
            return 0xFFC0C0C0;
        case CSSValueThreedhighlight:
            return 0xFFDDDDDD;
        case CSSValueThreedlightshadow:
            return 0xFFC0C0C0;
        case CSSValueThreedshadow:
            return 0xFF888888;
        case CSSValueWindow:
            return 0xFFFFFFFF;
        case CSSValueWindowframe:
            return 0xFFCCCCCC;
        case CSSValueWindowtext:
            return 0xFF000000;
        default:
            break;
    }
    return Color();
}

Color RenderTheme::platformActiveTextSearchHighlightColor() const
{
    return Color(255, 150, 50); // Orange.
}

Color RenderTheme::platformInactiveTextSearchHighlightColor() const
{
    return Color(255, 255, 0); // Yellow.
}

#if ENABLE(TOUCH_EVENTS)
Color RenderTheme::tapHighlightColor()
{
    return defaultTheme()->platformTapHighlightColor();
}
#endif

// Value chosen by observation. This can be tweaked.
static const int minColorContrastValue = 1300;
// For transparent or translucent background color, use lightening.
static const int minDisabledColorAlphaValue = 128;

Color RenderTheme::disabledTextColor(const Color& textColor, const Color& backgroundColor) const
{
    // The explicit check for black is an optimization for the 99% case (black on white).
    // This also means that black on black will turn into grey on black when disabled.
    Color disabledColor;
    if (textColor.rgb() == Color::black || backgroundColor.alpha() < minDisabledColorAlphaValue || differenceSquared(textColor, Color::white) > differenceSquared(backgroundColor, Color::white))
        disabledColor = textColor.light();
    else
        disabledColor = textColor.dark();
    
    // If there's not very much contrast between the disabled color and the background color,
    // just leave the text color alone. We don't want to change a good contrast color scheme so that it has really bad contrast.
    // If the the contrast was already poor, then it doesn't do any good to change it to a different poor contrast color scheme.
    if (differenceSquared(disabledColor, backgroundColor) < minColorContrastValue)
        return textColor;
    
    return disabledColor;
}

// Value chosen to return dark gray for both white on black and black on white.
constexpr float datePlaceholderColorLightnessAdjustmentFactor = 0.66f;

Color RenderTheme::datePlaceholderTextColor(const Color& textColor, const Color& backgroundColor) const
{
    // FIXME: Consider using LCHA<float> rather than HSLA<float> for better perceptual results and to avoid clamping to sRGB gamut, which is what HSLA does.
    FloatComponents hslComponents = sRGBToHSL(textColor);
    // adjust lightness components[2]
    if (textColor.luminance() < backgroundColor.luminance())
    	hslComponents.components[2] += datePlaceholderColorLightnessAdjustmentFactor * (1.0f - hslComponents.components[2]);
    else
    	hslComponents.components[2] *= datePlaceholderColorLightnessAdjustmentFactor;

    // FIXME: Consider keeping color in LCHA (if that change is made) or converting back to the initial underlying color type to avoid unnecessarily clamping colors outside of sRGB.

    // Convert back to RGB.
    FloatComponents sRGBColorComponents = HSLToSRGB(hslComponents);
    return Color(sRGBColorComponents.components[0], sRGBColorComponents.components[1], sRGBColorComponents.components[2], sRGBColorComponents.components[3]);
}

void RenderTheme::setCustomFocusRingColor(const Color& c)
{
    customFocusRingColor() = c;
}

Color RenderTheme::focusRingColor()
{
    return customFocusRingColor().isValid() ? customFocusRingColor() : defaultTheme()->platformFocusRingColor();
}

String RenderTheme::fileListDefaultLabel(bool multipleFilesAllowed) const
{
    if (multipleFilesAllowed)
        return fileButtonNoFilesSelectedLabel();
    return fileButtonNoFileSelectedLabel();
}

String RenderTheme::fileListNameForWidth(const FileList* fileList, const FontCascade& font, int width, bool multipleFilesAllowed) const
{
    if (width <= 0)
        return String();

    String string;
    if (fileList->isEmpty())
        string = fileListDefaultLabel(multipleFilesAllowed);
    else if (fileList->length() == 1)
        string = fileList->item(0)->name();
    else
        return StringTruncator::rightTruncate(multipleFileUploadText(fileList->length()), width, font);

    return StringTruncator::centerTruncate(string, width, font);
}

} // namespace WebCore
