/*
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2000 Dirk Mueller (mueller@kde.org)
 * Copyright (C) 2004-2026 Apple Inc. All rights reserved.
 * Copyright (C) 2010-2015 Google 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.
 *
 */

#pragma once

#include <WebCore/HTMLFormControlElement.h>
#include <WebCore/HTMLOptionElement.h>
#include <WebCore/PopupMenuClient.h>
#include <WebCore/TypeAhead.h>
#include <wtf/CompletionHandler.h>
#include <wtf/OptionSet.h>

#if PLATFORM(COCOA)
#define POPUP_MENU_PULLS_DOWN 0
#else
#define POPUP_MENU_PULLS_DOWN 1
#endif

namespace WebCore {

class HTMLOptionsCollection;
class SelectPopoverElement;
class ShadowRoot;

#if !PLATFORM(IOS_FAMILY)
class PopupMenu;
#endif

class HTMLSelectElement final : public HTMLFormControlElement, public PopupMenuClient, private TypeAheadDataSource {
    WTF_MAKE_TZONE_ALLOCATED(HTMLSelectElement);
    WTF_OVERRIDE_DELETE_FOR_CHECKED_PTR(HTMLSelectElement);
public:
    USING_CAN_MAKE_WEAKPTR(HTMLElement);

    // PopupMenuClient ref-counting (disambiguate from FormAssociatedElement)
    void ref() const final { HTMLFormControlElement::ref(); }
    void deref() const final { HTMLFormControlElement::deref(); }

    static Ref<HTMLSelectElement> create(const QualifiedName&, Document&);
    static Ref<HTMLSelectElement> create(Document&);
    ~HTMLSelectElement();

    enum class ExcludeOptGroup : bool { No, Yes };
    enum class PickerScrollMode : uint8_t { Nearest, AlignTop, AlignBottom };
    static HTMLSelectElement* NODELETE findOwnerSelect(ContainerNode*, ExcludeOptGroup);

    WEBCORE_EXPORT int selectedIndex() const;
    HTMLOptionElement* selectedOption();
    WEBCORE_EXPORT void setSelectedIndex(int);

    WEBCORE_EXPORT void optionSelectedByUser(int index, bool dispatchChangeEvent, bool allowMultipleSelection = false);

    String validationMessage() const final;
    bool valueMissing() const final;

    WEBCORE_EXPORT unsigned length() const;

    unsigned size() const { return m_size; }
    bool multiple() const { return m_multiple; }

    bool NODELETE usesMenuList() const;

    // This method is deprecated because the return value doesn't match the rendering on iOS for multiple selects.
    bool NODELETE usesMenuListDeprecated() const;

    using OptionOrOptGroupElement = Variant<Ref<HTMLOptionElement>, Ref<HTMLOptGroupElement>>;
    using HTMLElementOrInt = Variant<Ref<HTMLElement>, int>;
    WEBCORE_EXPORT ExceptionOr<void> add(const OptionOrOptGroupElement&, const std::optional<HTMLElementOrInt>& before);

    using Node::remove;
    WEBCORE_EXPORT void remove(int);

    WEBCORE_EXPORT String value() const;
    WEBCORE_EXPORT void setValue(const String&);

    enum class EmitNewlineForEmptyItems : bool { No, Yes };
    String collectOptionInnerText(EmitNewlineForEmptyItems = EmitNewlineForEmptyItems::No) const;

    WEBCORE_EXPORT Ref<HTMLOptionsCollection> options();
    Ref<HTMLCollection> selectedOptions();

    void optionElementChildrenChanged();
    void updateButtonText(HTMLOptionElement* = nullptr, int optionIndex = -1);
    void invalidateButtonText();

    void setRecalcListItems();
    void updateListItemSelectedStates(AllowStyleInvalidation = AllowStyleInvalidation::Yes);

    WEBCORE_EXPORT const Vector<WeakPtr<HTMLElement, WeakPtrImplWithEventTargetData>>& listItems() const LIFETIME_BOUND;

    void accessKeySetSelectedIndex(int);

    WEBCORE_EXPORT void setSize(unsigned);

    // Called by the bindings for the unnamed index-setter.
    ExceptionOr<void> setItem(unsigned index, HTMLOptionElement*);
    ExceptionOr<void> setLength(unsigned);

    ExceptionOr<void> showPicker();

    void showPopup();
#if !PLATFORM(IOS_FAMILY)
    void hidePopup();
#endif

    bool popupIsVisible() const { return m_popupIsVisible; }
    WEBCORE_EXPORT void setPopupIsVisible(bool);
    std::optional<FloatPoint> lastPopupLocationForTesting() const { return m_lastPopupLocationForTesting; }

    bool NODELETE isOpen() const;

    void didUpdateActiveOption(int optionIndex);

    // PopupMenuClient methods
    void valueChanged(unsigned listIndex, bool fireOnChange = true) override;
    String itemText(unsigned listIndex) const override;
    String itemToolTip(unsigned listIndex) const override;
    String itemAccessibilityText(unsigned listIndex) const override;
    bool itemIsEnabled(unsigned listIndex) const override;
    PopupMenuStyle itemStyle(unsigned listIndex) const override;
    PopupMenuStyle menuStyle() const override;
    int listSize() const override;
    void popupDidHide() override;
#if PLATFORM(WPE)
    void showFallbackPopupMenu() override;
#endif
    bool itemIsSeparator(unsigned listIndex) const override;
    bool itemIsLabel(unsigned listIndex) const override;
    bool itemIsSelected(unsigned listIndex) const override;
    bool shouldPopOver() const override { return !POPUP_MENU_PULLS_DOWN; }
#if !PLATFORM(COCOA)
    void setTextFromItem(unsigned listIndex) override;
#endif
#if PLATFORM(WIN)
    int clientInsetLeft() const override;
    int clientInsetRight() const override;
    LayoutUnit clientPaddingLeft() const override;
    LayoutUnit clientPaddingRight() const override;
    FontSelector* fontSelector() const override;
    HostWindow* hostWindow() const override;
#endif

    WEBCORE_EXPORT HTMLOptionElement* namedItem(const AtomString& name);
    WEBCORE_EXPORT HTMLOptionElement* item(unsigned index);
    bool isSupportedPropertyIndex(unsigned index);

    void scrollToSelection();
    void selectDefaultOptionIfNeeded(HTMLOptionElement&);

    bool canSelectAll() const { return m_multiple; }
    void selectAll();
    int listToOptionIndex(int listIndex) const;
    void listBoxOnChange();
    int optionToListIndex(int optionIndex) const;
    int activeSelectionStartListIndex() const;
    int activeSelectionEndListIndex() const;
    void setActiveSelectionAnchorIndex(int);
    void NODELETE setActiveSelectionEndIndex(int);
    void updateListBoxSelection(bool deselectOtherOptions);

    // For use in the implementation of HTMLOptionElement.
    void optionSelectionStateChanged(HTMLOptionElement&, bool optionIsSelected);
    bool allowsNonContiguousSelection() const { return m_allowsNonContiguousSelection; };

    CompletionHandlerCallingScope optionToSelectFromChildChangeScope(const ChildChange&, HTMLOptGroupElement* parentOptGroup = nullptr);

    bool canContainRangeEndPoint() const override { return false; }
    bool shouldSaveAndRestoreFormControlState() const final { return true; }

    bool isDevolvableWidget() const override { return true; }

    void updateSelectedContent(HTMLOptionElement* = nullptr) const;

    void NODELETE registerSelectedContentElement();
    void NODELETE unregisterSelectedContentElement();

    WEBCORE_EXPORT bool usesBaseAppearancePicker() const;
    SelectPopoverElement* NODELETE pickerPopoverElement() const;
    void openPickerForUserInteraction(std::optional<bool> focusVisible = std::nullopt);
    void hidePickerPopoverElement();
    void queuePickerCloseForAppearanceChange();

    struct NavigationKeyIdentifiers {
        ASCIILiteral next;
        ASCIILiteral previous;
        WritingMode writingMode { };
    };
    NavigationKeyIdentifiers pickerNavigationKeyIdentifiers() const;
    int computeNavigationIndex(const String& keyIdentifier, int currentListIndex, NavigationKeyIdentifiers) const;
    void focusOptionAtIndex(int listIndex, std::optional<bool> focusVisible = std::nullopt, PickerScrollMode = PickerScrollMode::Nearest);
    int typeAheadMatchIndex(KeyboardEvent&);

protected:
    HTMLSelectElement(const QualifiedName&, Document&);

private:
    const AtomString& formControlType() const final;

    int defaultTabIndex() const final;
    bool isKeyboardFocusable(const FocusEventData&) const final;
    bool isMouseFocusable() const final;
    bool NODELETE hasCustomFocusLogic() const final { return true; }

    void dispatchFocusEvent(RefPtr<Element>&& oldFocusedElement, const FocusOptions&) final;
    void dispatchBlurEvent(RefPtr<Element>&& newFocusedElement) final;
    
    bool canStartSelection() const final { return false; }

    bool NODELETE isEnumeratable() const final { return true; }
    bool isLabelable() const final { return true; }

    bool isInteractiveContent() const final { return true; }

    FormControlState saveFormControlState() const final;
    void restoreFormControlState(const FormControlState&) final;

    void attributeChanged(const QualifiedName&, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason) final;

    void setDisabledInternal(bool disabled, bool disabledByAncestorFieldset) final;

    bool hasPresentationalHintsForAttribute(const QualifiedName&) const final;

    bool childShouldCreateRenderer(const Node&) const final;
    RenderPtr<RenderElement> createElementRenderer(Style::ComputedStyle&&, const RenderTreePosition&) final;
    bool appendFormData(DOMFormData&) final;

    void reset() final;

    void defaultEventHandler(Event&) final;
    bool willRespondToMouseClickEventsWithEditability(Editability) const final;

    void dispatchChangeEventForMenuList();

    void didRecalcStyle(OptionSet<Style::Change>) final;

    void invalidateSelectedItems();
    void recalcListItems(bool updateSelectedStates = true, AllowStyleInvalidation = AllowStyleInvalidation::Yes) const;

    void typeAheadFind(KeyboardEvent&);
    void saveLastSelection();

    bool NODELETE isOptionalFormControl() const final { return !isRequiredFormControl(); }
    bool NODELETE isRequiredFormControl() const final;

    bool hasPlaceholderLabelOption() const;

    enum class SelectOptionFlag : uint8_t {
        DeselectOtherOptions = 1 << 0,
        DispatchChangeEvent = 1 << 1,
        UserDriven = 1 << 2,
    };
    void selectOption(int optionIndex, OptionSet<SelectOptionFlag> = { });
    void deselectItemsWithoutValidation(HTMLElement* elementToExclude = nullptr);
    void parseMultipleAttribute(const AtomString&);
    int lastSelectedListIndex() const;
    void updateSelectedState(int listIndex, bool multi, bool shift);
    void menuListDefaultEventHandler(Event&);
    bool platformHandleKeydownEvent(KeyboardEvent*);
    void listBoxDefaultEventHandler(Event&);
    void setOptionsChangedOnRenderer();
    size_t searchOptionsForValue(const String&, size_t listIndexStart, size_t listIndexEnd) const;

    enum class SkipDirection : bool { Backwards, Forwards };
    int nextValidIndex(int listIndex, SkipDirection, int skip) const;
    int nextSelectableListIndex(int startIndex) const;
    int previousSelectableListIndex(int startIndex) const;
    int firstSelectableListIndex() const;
    int lastSelectableListIndex() const;
    int nextSelectableListIndexPageAway(int startIndex, SkipDirection) const;
    int nextSelectableListIndexForPickerPageMove(int startIndex, SkipDirection, WritingMode) const;

    void childrenChanged(const ChildChange&) final;
    NeedsPostConnectionSteps insertionSteps(InsertionType, ContainerNode&) final;
    void removingSteps(RemovalType, ContainerNode&) final;
    void updateUserAgentShadowTree() final;

    void didDetachRenderers() final;

    void didAddUserAgentShadowRoot(ShadowRoot&) final;

    void showPickerInternal();

    // TypeAheadDataSource functions.
    int indexOfSelectedOption() const final;
    int optionCount() const final;
    String optionAtIndex(int index) const final;

    // m_listItems contains HTMLOptionElement, HTMLOptGroupElement, and HTMLHRElement objects.
    mutable Vector<WeakPtr<HTMLElement, WeakPtrImplWithEventTargetData>> m_listItems;
    Vector<bool> m_lastOnChangeSelection;
    Vector<bool> m_cachedStateForActiveSelection;
    TypeAhead m_typeAhead;
    unsigned m_size;
    int m_lastOnChangeIndex;
    int m_activeSelectionAnchorIndex;
    int m_activeSelectionEndIndex;
    bool m_isProcessingUserDrivenChange;
    bool m_multiple;
    bool m_activeSelectionState;
    bool m_allowsNonContiguousSelection;
    bool m_isCapturingMouseEvents { false };
    mutable bool m_shouldRecalcListItems;
    unsigned m_selectedContentDescendantCount { 0 };

    std::optional<int> m_lastActiveIndex;

    WeakPtr<HTMLSlotElement, WeakPtrImplWithEventTargetData> m_buttonSlot;
    WeakPtr<SelectPopoverElement, WeakPtrImplWithEventTargetData> m_popover;

#if !PLATFORM(IOS_FAMILY)
    RefPtr<PopupMenu> m_popup;
#endif
    std::optional<FloatPoint> m_lastPopupLocationForTesting;
    bool m_popupIsVisible { false };
    bool m_wasBaseAppearance { false };
    bool m_buttonTextNeedsUpdate { false };
};

} // namespace
