/* * Copyright (c) 2018-2020, Andreas Kling * Copyright (c) 2022, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #include #include #include #include #include #include #include #include #include #include REGISTER_WIDGET(GUI, ComboBox) namespace GUI { class ComboBoxEditor final : public TextEditor { C_OBJECT(ComboBoxEditor); public: Function on_mousewheel; Function on_keypress; private: ComboBoxEditor() : TextEditor(TextEditor::SingleLine) { } virtual void mousewheel_event(MouseEvent& event) override { if (!is_focused()) set_focus(true); if (on_mousewheel) on_mousewheel(event.wheel_delta_y()); event.accept(); } virtual void keydown_event(KeyEvent& event) override { if (event.key() == Key_Escape) { if (is_focused()) set_focus(false); event.accept(); } else { on_keypress(event); TextEditor::keydown_event(event); } } }; ComboBox::ComboBox() { REGISTER_DEPRECATED_STRING_PROPERTY("placeholder", editor_placeholder, set_editor_placeholder); REGISTER_BOOL_PROPERTY("model_only", only_allow_values_from_model, set_only_allow_values_from_model); REGISTER_INT_PROPERTY("max_visible_items", max_visible_items, set_max_visible_items); set_min_size({ 40, 22 }); set_preferred_size({ SpecialDimension::OpportunisticGrow, 22 }); m_editor = add(); m_editor->set_frame_style(Gfx::FrameStyle::NoFrame); m_editor->on_return_pressed = [this] { if (on_return_pressed) on_return_pressed(); }; m_editor->on_up_pressed = [this] { navigate(AbstractView::CursorMovement::Up); }; m_editor->on_down_pressed = [this] { navigate(AbstractView::CursorMovement::Down); }; m_editor->on_pageup_pressed = [this] { navigate(AbstractView::CursorMovement::PageUp); }; m_editor->on_pagedown_pressed = [this] { navigate(AbstractView::CursorMovement::PageDown); }; m_editor->on_mousewheel = [this](int delta) { // Since we can only show one item at a time we don't want to // skip any. So just move one item at a time. navigate_relative(delta > 0 ? 1 : -1); }; m_editor->on_mousedown = [this] { if (only_allow_values_from_model()) m_open_button->click(); }; m_editor->on_keypress = [this](KeyEvent& event) { if (!m_only_allow_values_from_model) return; if (!m_list_window->is_visible() && event.key() <= Key_Z && event.key() >= Key_A && event.modifiers() == Mod_None) { open(); m_list_window->event(event); } }; m_open_button = add