TextBox.cpp 2.3 KB

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