TextBox.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibGUI/TextBox.h>
  8. REGISTER_WIDGET(GUI, TextBox)
  9. REGISTER_WIDGET(GUI, PasswordBox)
  10. REGISTER_WIDGET(GUI, UrlBox)
  11. namespace GUI {
  12. TextBox::TextBox()
  13. : TextEditor(TextEditor::SingleLine)
  14. {
  15. set_min_width(32);
  16. set_fixed_height(22);
  17. }
  18. void TextBox::keydown_event(GUI::KeyEvent& event)
  19. {
  20. TextEditor::keydown_event(event);
  21. if (event.key() == Key_Up) {
  22. if (on_up_pressed)
  23. on_up_pressed();
  24. if (has_no_history() || !can_go_backwards_in_history())
  25. return;
  26. if (m_history_index >= static_cast<int>(m_history.size()))
  27. m_saved_input = text();
  28. m_history_index--;
  29. set_text(m_history[m_history_index]);
  30. } else if (event.key() == Key_Down) {
  31. if (on_down_pressed)
  32. on_down_pressed();
  33. if (has_no_history())
  34. return;
  35. if (can_go_forwards_in_history()) {
  36. m_history_index++;
  37. set_text(m_history[m_history_index]);
  38. } else if (m_history_index < static_cast<int>(m_history.size())) {
  39. m_history_index++;
  40. set_text(m_saved_input);
  41. }
  42. }
  43. }
  44. void TextBox::add_current_text_to_history()
  45. {
  46. if (!m_history_enabled)
  47. return;
  48. auto input = text();
  49. if (m_history.is_empty() || m_history.last() != input)
  50. add_input_to_history(input);
  51. m_history_index = static_cast<int>(m_history.size());
  52. m_saved_input = {};
  53. }
  54. void TextBox::add_input_to_history(String input)
  55. {
  56. m_history.append(move(input));
  57. m_history_index++;
  58. }
  59. PasswordBox::PasswordBox()
  60. : TextBox()
  61. {
  62. set_substitution_code_point('*');
  63. set_text_is_secret(true);
  64. }
  65. UrlBox::UrlBox()
  66. : TextBox()
  67. {
  68. set_auto_focusable(false);
  69. }
  70. void UrlBox::focusout_event(GUI::FocusEvent& event)
  71. {
  72. set_focus_transition(true);
  73. TextBox::focusout_event(event);
  74. }
  75. void UrlBox::mousedown_event(GUI::MouseEvent& event)
  76. {
  77. if (is_displayonly())
  78. return;
  79. if (event.button() != MouseButton::Primary)
  80. return;
  81. if (is_focus_transition()) {
  82. TextBox::select_current_line();
  83. set_focus_transition(false);
  84. } else {
  85. TextBox::mousedown_event(event);
  86. }
  87. }
  88. }